[solved]prime number (I have searched around)

I am having a problem =/ My program will determine if a input number is a prime until I enter something over 200 =/ I am not understanding it. 199 works fine but 205 comes back as prime even though I know divisible by 5 is NOT prime! I have looked around and compared to other codes in the search but I am not finding my difference =/ I am not asking for the code just the reason behind my problem =/ Here is my code:

#include <iostream>
//#include <iomanip>
#include <cmath>
using namespace std;

int main() {

int i, number;
double userNumber;
char continueLoop = 'Y';

while (continueLoop == 'Y')
{

cout << "Enter a positive number, greater then zero, you wish to "
<< "find out is prime " << endl;
cin >> userNumber;

while (userNumber < 0) {
cout << "Invalid Entry! Please reread the instructions and try again."
<< endl;
cout << "Enter a positive number you wish to find out if is "
<< "prime (greater then zero): " << endl;
cin >> userNumber;
} //end while

if (int (userNumber)% 2 == 0)
number = 0; // not prime

else{

for(i = 3; i <= sqrt(userNumber); i +=2) {

if (int (userNumber) % i == 0){
number = 0;} // not prime
else{
number = 1;} // is prime
} // end for
} // end else
cout << "\n\n";
if (number == 0)
cout << userNumber << " is not a prime number." << endl;

else
cout << userNumber << " is a prime number!" << endl;

cout<<"\nDo you want to continue? (Y) ";
cin >> continueLoop;
cout << endl;
continueLoop = toupper(continueLoop);
}//end of continueLoop

return 0;
} //end main


Side question: How do you set it up so when I copy my code it shows the line numbers when pasting like a few of you do? lol
Last edited on
Use [code][/code] tags.

The problem is that you're not stopping the search for divisors after you've found that userNumber is divisible by some value of i. The result is that you're only checking whether userNumber is divisible by sqrt(userNumber).
Thanks a ton! I finally figured it out with your help! All I needed was a to add a break after it found a divisor like you said! Such as easy fix!

1
2
3
4
		if (int(userNumber)%i == 0){
			number = 0; // not prime!
		break;}   //my nemesis this project!
		else{


and thanks for the code tags info too helios =]
Last edited on
Topic archived. No new replies allowed.