我正在尝试计算前n个数字的平方和。这是代码:
fun sumSq 0 = 0 |
sumSq x = x + sumSq(x * x-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!!!
你有一个无限循环