Advertisement
raedr7n

p1, cs430 - 22

Dec 20th, 2021 (edited)
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.17 KB | None | 0 0
  1. # Alexander Lucas
  2.  
  3. def factors(n)
  4.   ((n < 0 ? n : 1)..n.abs).select { |x| x != 0 && n % x == 0 }
  5. end
  6.  
  7. def primes(n)
  8.   nums = n < 2 ? (return []; []) : (2..n).to_a
  9.   nums.each do |x|
  10.     nums.drop(nums.find_index(x) + 1).each do |y|
  11.       nums.delete(y) if y % x == 0
  12.     end
  13.   end
  14. end
  15.  
  16. def prime_factors(n)
  17.   factors(n) & primes(n)
  18. end
  19.  
  20. def perfects(n)
  21.   prime_bound = Integer((Math.log((0.5)*Math.sqrt(8*n+1)+1))/(Math.log(2)))
  22.   primes(prime_bound).map do |x| 2**(x-1)*(2**x-1) end
  23. end
  24.  
  25. def pythagoreans(n)
  26.   return [] if n < 1
  27.  
  28.   (a, b, c, d) = [0, 1, 1, n]
  29.   ans = []
  30.   while c <= n do
  31.     k = (n + b) / d
  32.     (a, b, c, d) = [c, d, k*c-a, k*d-b]
  33.     ans << [a, b]
  34.   end
  35.  
  36.   ans = ans
  37.     .map do |x| x << Math.sqrt((x[0]*x[0]) + (x[1]*x[1])) end
  38.     .select do |x| x[2] % 1 == 0 && x[2] <= n end
  39.     .map do |x| x[0..1] << Integer(x[2]) end
  40.  
  41.   def aprims(triple, limit)
  42.     2.upto(limit).map do |x|
  43.       (a, b, c) = triple; [x*a, x*b, x*c]
  44.     end .reject do |(_, _, c)|
  45.       c > limit
  46.     end
  47.   end
  48.  
  49.   (0..ans.length - 1).each do |i|
  50.     ads = aprims(ans[i], n)
  51.     ads.each do |x|
  52.       ans << x
  53.     end
  54.   end
  55.  
  56.   ans.sort
  57. end
  58. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement