Sunday, 1 May 2016

How to check if a number is the perfect square ?


Note : A Perfect square is the Sum of all consecutive add numbers
Example of perfect squares : 1+3+5....

Algorithm
boolean isPerfectSquare = false;
int sum = 0;
// iterate from 1 to n incremented by 2
for(int i=1; sum<num; i+=2) {
    // Calculate the sum and check for perfect square
    sum += i;
    if (sum == num)
        isPerfectSquare = true;
        break;
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.