Graeme
Graeme

Reputation: 41

Where am I going wrong with this code?

I am trying to calculate the sum of the squares of the first n numbers. Here is the code:

fun sumSq 0 = 0 |
    sumSq x = x + sumSq(x * x-1);

I am getting an uncaught exception Overflow[overflow] error.

Upvotes: 0

Views: 323

Answers (1)

sonia
sonia

Reputation: 106

sumSq( x * x-1) is exactly the same than sumSq( (x * x) - 1) and not like sumSq( x * (x - 1)).

Consequences :

   if x = 0 or 1 it's ok.
   if x is greater than 1 (5 for example) 

   sumSq 5 = 5 + sumSq( 5 * 5-1 ) = 5 + sumSq(24) x will never decrease!!!

you have got an infinite loop

Upvotes: 1

Related Questions