What should I do when 'more than one instance of overloaded function "sqrt" matches the argument list'?

user1231810 picture user1231810 · Feb 25, 2012 · Viewed 8.4k times · Source

I get an error in my code in the for loop, for ( j = 3; j <=sqrt(num); j +=2):

more than one instance of overloaded function "sqrt" matches the argument list.

How do I resolve that?

# include <cmath>

// determine if number is prime
bool isPrime (long n) 
{
  int j, num = 0;
  {
    if (num <=1)
      return false;
  }
  for ( j = 3; j <=sqrt(num); j +=2)
  {
    if (num % j == 0)
      return false;
  }   
  return true;
}

Answer

mfontanini picture mfontanini · Feb 25, 2012

Try:

for (j = 3; j <= std::sqrt(static_cast<float>(num)); j +=2)

What is happening is that <cmath> contains 3 different definitions of sqrt and the compiler doesn't know which one you are trying to use.