-
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;
}
Last edited by 2kaud; 09-10-2019 at 04:17 AM.
Reason: Added code tags
-
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);
Last edited by 2kaud; 09-10-2019 at 04:35 AM.
-
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.
Similar Threads
-
By pirateninja in forum C++
Replies: 3
Last Post: 06-18-2007, 08:43 AM
-
Replies: 5
Last Post: 11-23-2005, 10:10 AM
-
By xxxxx in forum ASP.NET
Replies: 2
Last Post: 07-28-2005, 03:44 AM
-
By Danny Kalev in forum C++
Replies: 0
Last Post: 07-21-2000, 08:36 AM
-
By Helder Simões in forum C++
Replies: 0
Last Post: 07-21-2000, 06:27 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|