Originally Posted by
nitro_n2o
That sounds like iterating forever!!!
I'm not a ruby expert but try:
end until x*x < number
there are no prime factors greater than the sqrt of the number
I thought of doing that but I didn't remember if it was mathematically right.
Thanks nitro, I'm going to try it out and see if it works now.
EDIT: I tried out x*x > number (it's > and not < because it continues until the number is bigger than that, not while it is smaller)
but then I thought x > Math.sqrt(number) was more elegant and gave the same result and preferred to keep it that way.
And just for the heck of it,
here's the problem:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 317584931803?
And here is my solution using Ruby:
Code:
factors = []
primes = []
nonprimes = []
largest = 0
x = 2
number = 317584931803
begin
if(number%x==0)
factors << x
end
x+=1
end until x > Math.sqrt(number)
puts factors
for i in factors
for x in 2...i
if((i%x==0)&&(nonprimes.index(i)==nil))
nonprimes << i
puts "#{i.to_s} is a non-prime factor"
end
end
end
primes = factors - nonprimes
puts primes
largest = primes.max
puts "The largest prime factor of 317584931803 is #{largest.to_s}"
Bookmarks