HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Checking if a number is a perfect square (without Math)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutnumberperfectcheckingmathsquare

Problem

I typed this up quickly as an intuitive solution for determining if a given number is a perfect square.

How could I improve this? I already know that it doesn't handle the case where the number is 1. I'm wondering if I could generalize the calculation so it rounds up. What can I look into to develop a mindset for tackling these sorts of problems?

int number = 1000000;
int half = (number + 2 - 1)/2;
int square = 0;
boolean isSquare = false;

for( int i = half; i > 0 ; i-- ){

    square = i*i;

    if( square > number )
        continue;

    if( square == number ){
        System.out.println( "This number is a perfect square" );
        isSquare = true;
        break;
    } 

}

if( !isSquare ){
    System.out.println( "This number is not a perfect square" );
}

Solution

You could make use of the fact that n² = the sum of the first n odd numbers (for integral n ≥ 0), rather than having to compute i * i every time through the loop.

Context

StackExchange Code Review Q#29100, answer score: 7

Revisions (0)

No revisions yet.