I'm new with C++ and need help with prime numbers. I need to write a program that determines whether a number is a prime number or not. Here's what my code currently looks like:
#include <iostream>
#include <iomanip>
#include <cmath>
usingnamespace std;
int IsPrime(int num)
{
for(int i = 2; i <= sqrt((double)num); i++)
{
int ans;
if((num % i) == 0 && (i!=1 && i!=num))
ans = 0;
else
ans = 1;
return ans;
}
}
int main ()
{
int Number;
char ContinueLoop = 'Y';
while (ContinueLoop == 'Y')
{
cout <<endl<<endl
<<"Please enter a number: ";
cin >> Number;
{
int ans = IsPrime(Number);
if (ans == 0)
cout<<"The number is not a prime number";
else
cout<<"The number is a prime number";
}
cout<<"\nDo you want to continue? (Y) ";
cin>>ContinueLoop;
cout<<endl;
ContinueLoop = toupper(ContinueLoop);
}//end of ContinueLoop
cout<<"\nGood-bye!";
return 0;
}
When I test 15 and 21, my code claims they are prime number (ugh!). Any suggestions for how to determine a prime or if I did something wrong with my code would be appreciated. Thank you
int IsPrime(int num)
{
int ans=1;
for(int i = 2; i <= num/2; i++)
{
if(num % i == 0)
{
ans = 0;
break;
}
}
return ans;
}
PS: This is not the fastest program. For a discussion on the time/space complexity of PRIMES, please see the thread: "Prime number program" by doom at http://www.cplusplus.com/forum/general/1125/
Turkeycatmom: In addition to being able to use this code, please understand why your code does not work. That would help you write your code correctly on your own.