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
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
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.
Well it recursively calculates
x2 + (x-1)2 + (x-2)2 + ⋯ + 22 + 1.
This is the sum of squares of natural numbers. The sum of first
n natural numbers can be represented mathematically by: