Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

primes - Ruby puts not outputting in real time

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try adding a STDOUT.sync = true. You could also try STDOUT.flush after the puts. Some more info here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...