Sat06Feb

  1. Project Euler in Ruby: Problem #3

    Problem

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

    What is the largest prime factor of the number 600851475143?

    Solution

    require 'mathn'
    class Integer
      def largest_prime_factor
        number = self
        prime = Prime.new
        divisor = prime.succ
        while divisor < number
          number /= divisor if number % divisor == 0
          divisor = prime.succ
        end
        divisor
      end
    end
    
    puts 600851475143.largest_prime_factor
    

    In a real application I wouldn’t monkey patch a core class for something such as this, but for this example the OO style makes more sense to me, readability wise to me than a functional solution.