Does this function means its calculating x=(x-1) + x^2?
Function unknown(x)
if ( x == 1 )
return 1
else
return unknown(x‐1) + x*x
Does this function means its calculating x=(x-1) + x^2?
Function unknown(x)
if ( x == 1 )
return 1
else
return unknown(x‐1) + x*x
This is the sum of squares of natural numbers. The sum of first n
natural numbers can be represented mathematically by:
n*(n+1)*(2n+1)/6
The function can be written in a more mathematical form as:
unknown(1) = 1
unknown(x) = unknown(x - 1) + x * x [if x is not 1]
To see why this is the same as the sum of squares, you can substitute the second line into itself recursively and observe the pattern that emerges:
unknown(x) = unknown(x - 1) + x * x
unknown(x) = unknown(x - 2) + (x - 1) * (x - 1) + x * x
unknown(x) = unknown(x - 3) + (x - 2) * (x - 2) + (x - 1) * (x - 1) + x * x
etc ...
After expanding several times, you find that eventually* you will reach the special case of unknown(1)
since the argument is steadily decreasing by one at each expansion. Hence,
(after expanding many times ...)
unknown(x) = unknown(1) + 2 * 2 + ... + (x - 1) * (x - 1) + x * x
unknown(x) = 1 + 2 * 2 + ... + (x - 1) * (x - 1) + x * x
Hence, this is simply the sum of squares.
[*] Unless your initial x
is less than one, in which case the function diverges (never terminates) since the argument will just keep becoming more and more negative.