Perfect square, not so perfect

0

I need to know if the sum of two numbers is a perfect square, I thought of adding the two and taking the root and then checking if the rest of the division by 1 is greater than zero, except that the operator (%) only works with integers and sqrt does not return me int, someone has a better idea or knows how can I build my own MOD function?

if(sqrt(a+b)%1==0) ...
    
asked by anonymous 03.10.2015 / 22:43

3 answers

1

One possibility is to do a binary search. So you do not need to use float.

unsigned intSqrt(int N){
    // invariante: lo*lo <= N < hi*hi
    unsigned lo = 0;     
    unsigned hi = 1<<16;
    while(hi - lo > 1){
        unsigned mid = (lo + hi)/2;
        unsigned mid2 = mid*mid;
        if( mid2 < N ){
            lo = mid;
        }else if(mid2 == N){
            return mid;
        }else{ // N < mid2
            hi = mid;
        }
    }
    return lo;
}

int quadradoPerfeito(unsigned N){
   int x = intSqrt(N);
   return x*x == N;
}
    
04.10.2015 / 03:30
1

int quadperfeito(int n)
{
    return (sqrt(n)-((int)sqrt(n)) == 0);
}

int somaEhQuadperfeito(int m, int n)
{
    return quadperfeito(m+n);
}
    
03.10.2015 / 23:37
-1

I found a solution:

int raiz_int = sqrt(a+b); 
double raiz_double = sqrt(a+b); 
if (raiz_int == raiz_double) ... ;
else ...

Not the best way but

    
03.10.2015 / 23:00