Euler 003 ruby Solution

Largest prime factor

Problem

https://projecteuler.net/problem=3

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143?

Answer: 6857

Solution

euler003.rb

#!/usr/bin/env ruby
def largest_prime_number(upper)
  answer = 2
  point = 3
  divisor = upper

  divisor /= 2 while divisor.even?

  while divisor != 1
    while (divisor % point) == 0
      answer = point
      divisor /= point
    end
    point += 2
  end
  answer
end

puts largest_prime_number(600_851_475_143) if __FILE__ == $PROGRAM_NAME

See Also

# cpp go java php ruby rust javascript
1
2
3  
4    
5    
6      
7          
8          
9          
10          
11          
12          
# cpp ruby
13
14
15
16
17
18
19
20  
21  
22  
23  
24