Home > Enterprise >  do..while loop not terminating
do..while loop not terminating

Time:09-21

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.

  1. Start with the root of sq in an integer, which can be rounded off.
  2. compare the square of root, rsq, with sq
  3. If it's smaller, increase root and compare again
  4. If it is the same, sq is a perfect square (of root) and we can return the next square
  5. 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;
}
  •  Tags:  
  • c
  • Related