In order to implement the square operation as a recursive function, you need first to express the operation in terms of itself:
(n-1)2 = n2 - 2n + 1 -->
n2 = (n-1)2 + 2n - 1
Then, in order to avoid the operator *
:
2n = n + n
Therefore, n2 = (n-1)2 + n + n - 1
With that in mind, you can easily implement square()
as a recursive function that does not use the operator *
:
unsigned int square(unsigned int n) {
if (n == 0)
return 0; // base case
return square(n-1) + n + n - 1; // recursive case
}
Or just with a single statement using the ternary operator:
unsigned int square(unsigned int n) {
return n? square(n-1) + n + n - 1: 0;
}
n
equal to zero is the base case (i.e., when the recursion stops). It returns zero for this case, since 02 is zero.