I am trying to find if the given number is a perfect square, and if so find the next perfect square for this codewars problem.
#include <cmath>
using namespace std;
long int findNextSquare(long int sq) {
// Return the next square if sq if a perfect square, -1 otherwise
long int k = sq;
do{
k ;
//cout << round(sqrt(k)) << endl;
//cout << k << endl;
}while(pow(round(sqrt(k)), 2) != k);
if(pow(sqrt(sq), 2) == sq)
return k;
else
return -1;
}
I am not sure why my loop is not terminating once k = 144
. Printing out k
and round(sqrt(k))
shows that after k = 144
, it jumps to 626
, for which I also do not know the reason.
CodePudding user response:
You should never try to check if a float is equal to an integer (or float) as a looping condition, as there are likely rounding problems (leading to infinite loops). That means you need to reformulate your problem using only integers.
- Start with the
root
ofsq
in an integer, which can be rounded off. - compare the
square
ofroot
,rsq
, withsq
- If it's smaller, increase
root
and compare again - If it is the same,
sq
is a perfect square (ofroot
) and we can return the next square - If its bigger,
sq
is not a perfect square: return -1.
That could lead to something like:
static long next_square(long sq) {
long root = sqrt(sq);
long rootSquared = root * root;
while (rootSquared < sq) {
root ;
rootSquared = root * root;
}
if (rootSquared == sq) {
root ;
return root * root;
}
return -1;
}