I've started some problems on Project Euler. One of the questions:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
I have some code written up...and it works:
class Integer
def primeFactors
load('/home/arseno/ruby/lib/prime.rb')
a = []
for i in (1..self)
div = self.to_f/i.to_f
if((div==div.to_i)&&(Prime.prime?(i)))
a << i
end
end
a
end
end
puts 13195.primeFactors
Outputs:
5
7
13
29
So far so good! Now, when I put in 600851475143 instead, my terminal hangs up (rightfully so, it's computing a whole lot of stuff!) So what I attempted to do was to put a puts i
within the loop/if, so that I capture the output as it iterated through...in real time.
But by putting this puts i
into the loop, Ruby does not output the variable throughout the iteration; instead, it holds onto the values in some kind of buffer and flushes them out when the computation is complete.
This particular problem is taking forever for Ruby to compute (it's been running for 10 minutes), I suspect it is in the float conversions.
Why is Ruby (my Terminal?) holding onto the values until end of computation? Can I see the values in real time as it finds them instead? Do you have a better way of doing this?
Try adding a
STDOUT.sync = true
. You could also trySTDOUT.flush
after theputs
. Some more info here.