简体   繁体   中英

proving the correctness of this recursive algorithm using induction

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM