0

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.

Graeme
  • 41
  • 2

1 Answers1

1

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

sonia
  • 106
  • 4