Thursday, 7 April 2016

Check perfect square using addition/subtraction

Property: Sum of all consecutive odd number always a perfect square.

Proof:
1 + 3 + 5 + ...  (2n-1) = n/2*[ 1+ (2n-1)] = n/2*[2n]
                        = n^2

Sum of A.P. = terms/2*{first_term+last_term}

Using this property, we can write the pseudo code:


boolean  perfectSqr(int num) {
       int sum = 0;
       for(int i=1; sum<num; i+=2) {
                    sum += i;
                    if (sum == num)
                             return true;
                             break;
                    }
       }
       return false;
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...