0
int sumHelper(int n, int a) {
   if (n==0) return a;
   else return sumHelper(n-1, a + n*n);
}

int sumSqr(int n) { 
    return sumHelper(n, 0); 
}

Guys, I am supposed to prove this piece of code which uses tail recursion to sum up the square of numbers. ie, Prove that for n ≥ 1,sumsqr(n)=1^2+2^2+...n^2. I have figured out the base case but I am stuck at the induction step. Any hints or help will be appreciated.

Mokarrom Hossain
  • 357
  • 1
  • 11
Manny
  • 11
  • 1
  • 5
  • This is a purely mathematical question. I would vote it as off-topic. Yes, there is code but the code is simply the implementation of a mathematical algorithm. – Ben May 15 '18 at 15:14
  • I think this might be more appropriate for one of the computer science stack exchanges. – Mark Rotteveel May 15 '18 at 15:22

1 Answers1

0

It works for base case, as you proved. Imagine that it works for n. Suppose it works for n+1. As it works for n, if n == 0 we get all sum of squares. Now we can think about additional methods which was invoked for n+1. And it would be only first one, return sumHelper(n, a + (n+1)^2). All other methods will be thrown just like in n. So we have a = sum of squares 1 to n and (n+1)^2, so it obviously works as you predicted.

Hubert Bratek
  • 894
  • 10
  • 30