java.lang.ArithmeticException: Negative exponent in jruby

553 views Asked by At

I have the following JRuby code :

def knuth(a, n, b)
   if n ==1
      r = a**b
   else
      r = 1
      b.times do
         r = knuth a, n-1, r
      end
   end
   return r
end
k = knuth 3, 4, 5
puts k
puts k.size

But it give me

java.lang.ArithmeticException: Negative exponent

any idea why ?

I'm on Windows and using jruby-9.0.0.0.pre2-p0

1

There are 1 answers

4
neuronaut On

There are two things at work here. First, in the JVM all numbers are signed. Thus, when r grows large enough that the high-order bit gets set the number actually becomes negative, hence the error. The second thing is that each time you go through the b.times loop r is being reassigned such that during the next iteration the value of r being passed to knuth is much larger, causing the new value for r to again be greatly increased and so on until r becomes negative.