Question: Devise a recursive algorithm for computing n 2 where n is a nonnegative integer, using the fact that ( n + 1 ) 2 =

Devise a recursive algorithm for computing n2 where n is a nonnegative integer, using the fact that (n+1)2=n2+2n+1. Then
prove that this algorithm is correct.
procedure square(n : nonnegative integer)
if n=0 then return 0
else return square (n-1)+2(n-1)+1
Let P(n) be the statement that this algorithm correctly computes n2. Because 02=0, the algorithm works correctly
(using the if clause) if the input is 0. Assume that the algorithm works correctly for input k. Then for input k+1, it
gives as output (because of the else clause) its output when the input is k, plus 2(k+1-1)+1. By the inductive
hypothesis, its output at k is k2, so its output at k+1 is k2+2(k+1-1)+1=k2+2k+1=(k+1)2, as desired.
Devise a recursive algorithm for computing n 2

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!