# Having a problem with calling the sqrt function trying to pass an integer

Printable View

• 09-08-2019, 12:53 PM
Dioxazine
Having a problem with calling the sqrt function trying to pass an integer
I'm having a problem calling the sqrt function in my prime number checker program. My intention is to make the for loop only check up to the square root of the number the user has entered. But C++ Builder is telling me there is ambiguity between sqrt(double) and sqrt(long double).

I want to pass an integer to the sqrt function but I don't know if I can. Cast it to an int perhaps?

Here is what I got:

Code:

```#include <iostream> #include <cmath> #include <conio.h> using namespace std; bool isPrime(int num); int main() {         int x;         bool flag;         cout << "Enter a positive integer: ";         cin >> x;         flag = isPrime(x);         if (flag == true)                 cout << x << " is a prime number" << endl;         else                 cout << x << " is not a prime number" << endl;         getch();         return 0; } bool isPrime(int num) {         bool flag;         for (int i = 2; i <= sqrt(num); i++)                 if(num % i == 0)                 {                         flag = false;                         break;                 }         return flag; }```
• 09-10-2019, 04:32 AM
2kaud
The sqrt() function is not a 'quick' function, and as the value of its argument doesn't change it is better if this value was computed outside of the for loop.

sqrt() can take an int value, but returns a type double. I use MS VS2019 and the above code compiles OK for me.

You are also using flag without first initialising it. if the break in the for loop is never executed, flag will have whatever value it happens to be initialised to at the start of the program.

This compiles OK for me with MS VS2019:

Code:

```bool isPrime(int num) {         bool flag = true;         const int srt = (int)sqrt(num);         for (int i = 2; i <= srt; i++)                 if (num % i == 0)                 {                         flag = false;                         break;                 }         return flag; }```
if you are still getting the ambiguity error, then try

Code:

`const int srt = (int)sqrt((double)num);`
• 09-10-2019, 07:11 AM
2kaud
PS. As a prime is never even, you can improve the performance of the loop by first testing num for even. If it is, then it's not a prime. If it's not, then the initial value of i can be 3 and i incremented by 2 rather than 1.
• 02-14-2021, 11:29 AM
mikaha21
Its better to use a double type variable when using sqrt function
• 03-13-2021, 12:42 PM
finlay31
Yes , i think long double variable will be better when we take numerically smaller decimal values as input
• 03-13-2021, 01:35 PM
2kaud
Since C++11, sqrt() accepts integral types which are internally cast to double.