Solving Algorithms – Largest prime factor

Today I solved this algorithm that is the third problem in Project Euler.
This still need some improvement, because even when the last prime number is found it still counts and takes a really long time when given big numbers.

require 'prime'

def largestPrime(num)
  result = 0
  (2...num).each do |i|
    result = i if (num % i) == 0 && i.prime?
  end
  puts result
end

largestPrime(13195)

I will update this code as soon as I find a better solution but for now it works.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s