Large multiplication output coming out negative in

2019-06-26 05:45发布

问题:

I wrote some code that is supposed to sum n^n for 1 <= n <= 1000. Here's the code:

sum = 0
(1..1000).each do |n|
  sum += n**n
  puts "n = #{n}, sum = #{sum}"
end

For some reason, the output is coming out negative after number 28:

n = 29, sum = -2015400977700573523892329442490139437391867

Any idea why this is happening?

回答1:

Looks like this was a bug in 1.8.7 that was fixed by patch 358: Exponentiation in Ruby 1.8.7 Returns Wrong Answers

(The result of a power computation in numeric.c wasn't declared as volatile before this commit, after which overflow behavior seems to have been fixed.)