Hello everyone. This is my first post here and first time programming C++. I am learning from a book and can't get this example to compile. It is supposed to determine whether or not a number entered by the user is prime or not.
#include <iostream>
#include <cmath>
usingnamespace std;
int main() {
int n; // Number to test for prime-ness
int i; // Loop counter
int is_prime = true; // Boolean flag...
// Get a number from the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime by checking for divisibility
// by all whole numbers from 2 to sqrt(n).
i = 2;
while (i <= sqrt(n)) { // While i is <= sqrt(n),
if (n % i == 0) // If i divides n,
is_prime = false; // n is not prime.
i++; // Add 1 to i.
}
// Print results
if (is_prime)
cout << "Number is prime." << endl;
else
cout << "Number is not prime." << endl;
system("PAUSE");
return 0;
}
The error I am getting says: "call of overloaded 'sqrt(int&)' is ambiguous" on line 17, which is the one with the "while" expression.
Sorry for my newbie question and thank you in advance for any help! :)
P.S. I am using Dev-C++ 4.9.8.0
There are several sqrt functions. One for float, double and long double. There is not sqrt for int. Normally the compiler would perform a cast, but now it doesn't know whether to cast to float or double. You need to cast it yourself: i <= sqrt((float)n) (there are several other ways to write this, like float(n), static_cast<float>(n) or even n*1.0//this casts results in double, write 1.0f for float .)
By the way, a faster way to write the same thing would be i*i <= n.
Thank you so much! I couldn't get it to work with i <= sqrt((float)n) but i*i <= n works great and makes more sense! :) Any idea why it won't work the other way, though? Is it because i is declared as an int at the top? Here is the code and my errors:
#include <iostream>
#include <cmath>
usingnamespace std;
int main() {
int n; // Number to test for prime-ness
float i; // Loop counter
int is_prime = true; // Boolean flag...
// Get a number from the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime by checking for divisibility
// by all whole numbers from 2 to sqrt(n).
i = 2;
while (i <= sqrt((float)n) { // While i is <= sqrt(n),
if (n % i == 0) { // If i divides n,
is_prime = false;
break;
} // n is not prime.
i++; // Add 1 to i.
}
// Print results
if (is_prime)
cout << "Number is prime." << endl;
else
cout << "Number is not prime." << endl;
system("PAUSE");
return 0;
}
// prime.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
usingnamespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int num;
char ch;
do
{
int factors=0;
cout<<"Enter a number ";
cin>>num;
for(int i=1;i<=num/2;i++)
{
if(num%i==0)
{
factors++;
}
}
if(factors>1)
cout<<num<<" is not a prime number"<<endl;
else
cout<<num<<" is a prime number"<<endl;
cout<<"Do you want to do it again ";
cin>>ch;
}
while(ch=='y' || ch=='Y');
return 0;
}