Dec 17, 2008

How to test whether a number is perfect square ?

How to test whether a number is perfect square ?

use binary search to check whether the number is perfect square

bool foo(int low,int high,int num)
{
if(low>high)
return false;
int mid=(low+high)/2;
if(mid*mid==num)
return true;
if(mid*mid<num)
return foo(mid+1,high,num);
return foo(low,mid-1,num);

}

note the perfect square has odd factors

No comments:

Post a Comment