Perfect square, not so perfect

Asked

Viewed 146 times

0

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

if(sqrt(a+b)%1==0) ...
  • What is the language?

  • I’m using the liguagem c

  • int tentativa = sqrt(valor); if (tentativa * tentativa == valor) /* quadrado perfeito */;

3 answers

1


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

int somaEhQuadperfeito(int m, int n)
{
    return quadperfeito(m+n);
}

1

One possibility is to do a binary search. So you don’t 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;
}

-1

I found a solution:

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

It’s not the best way but it’ll do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.