这个代码我哪里错了?

时间:2012-11-27 09:42:42

标签: sml smlnj

我正在尝试计算前n个数字的平方和。这是代码:

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

我收到一个未捕获的异常溢出[溢出]错误。

1 个答案:

答案 0 :(得分:1)

sumSq(x * x-1)与sumSq((x * x) - 1)完全相同,而不像sumSq(x *(x - 1))。

后果:

   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!!!

你有一个无限循环