# What does this function do?

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
``````
• Why is this tagged [array] and what language is it supposed to be? – JensG Sep 6 '14 at 12:45
• opps sorry. It's pseudocode. Once I know what is the function is doing, I will then know how to write it into C++/C#. – Zainu Sep 6 '14 at 12:53
• Have a look at this: programmers.stackexchange.com/questions/25052/… – 11684 Sep 6 '14 at 12:54
• Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask – gnat Sep 6 '14 at 18:20

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:

``````n*(n+1)*(2n+1)/6
``````