sutterhome1971
sutterhome1971

Reputation: 400

simple recursive function error - java.lang.StackOverFlow error - output exceeds cut off limit

I am practicing scala's simple recursive function. This is from a book

def calculatePower(x:Int, y:Int): Long = {

     if (x>=1)
         x*calculatePower(x,y-1)

     else 1

  }


calculatePower(2,2)

Upvotes: 0

Views: 36

Answers (2)

pedrofurla
pedrofurla

Reputation: 12783

Your method stack overflows because it doesn't terminate and the stack frames accumulates until there is no more room.

if (x>=1) x*calculatePower(x,y-1) You test if x is greater or equal to 1 but in the recursive call you only decrement y!

Upvotes: 0

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6182

You are checking x but you are decrementing y. That means your base-case will never be reached.

Upvotes: 2

Related Questions