Permalink
Browse files

Add a solution to EP 3 in Ruby

  • Loading branch information...
1 parent 3e5a269 commit dc1592a5b03fe959d6de9866d6394cc51fbc1889 @leto leto committed Aug 9, 2012
Showing with 29 additions and 0 deletions.
  1. +29 −0 ruby/003/01.rb
View
@@ -0,0 +1,29 @@
+#!/usr/bin/env ruby
+
+# Find the largest prime factor of 600851475143
+
+n = 600851475143
+
+def factors(n)
+ factors = [ ]
+ bound = Math.sqrt(n).floor
+ (2..bound).each do |x|
+ if n % x == 0
+ factors.push(x, n/x)
+ end
+ end
+ return factors
+end
+
+def prime_factors(n)
+ prime_factors = [ ]
+ f = factors(n).sort
+
+ f.map { |x|
+ if factors(x) == [ ]
+ prime_factors.push(x)
+ end
+ }
+ prime_factors.last
+end
+puts prime_factors(n)

0 comments on commit dc1592a

Please sign in to comment.