문제

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?

도움이 되었습니까?

해결책

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.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top