By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,506 Members | 1,891 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,506 IT Pros & Developers. It's quick & easy.

I have a program that decides if a given number is prime or not but it isnt working

P: 6
This is my code and it will take any number that I input and say it is a prime number. Please help me...



int Prime(int prime) //declares isPrime as a function using integers
{

int primeCount = 2; //declares primeCount as an int variable and sets it equal to 2
while(primeCount < prime) //checks if primeCount is less than prime
{
if((prime % primeCount) == 0) //checks if prime divided by primeCount has a remainder
{
cout<<"This number is not prime"<<endl; //prints "The number is not prime." on the screen
return 0; //ends program
}
else //if prime divided by primecount does have a remainder
primeCount++; //adds one to primeCount
} //once primeCount is equal to prime...
cout<<"This number is prime."<<endl; //prints "The number is prime." on the screen
return 0; //ends program

}
Nov 12 '06 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 1,510
when I run you code it appears to work OK, are you sure you are calling the function Prime() with the correct data? - put a statement inside Prime to print the value of the parameter to check it is correct, e.g.
cout << prime << endl;
Nov 12 '06 #2

100+
P: 175
i don't quite follow what you're trying to do, but part of the problem is that you're not checking if it's divisible by 3. Here's is some code that finds if ANY number is a prime number. It should help you out...

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int main() 
  6. {
  7.      int number(0); // sets the input number to 0
  8.  
  9.      while ( number != 99 )  // just picked a random condition to keep it looping
  10.      {
  11.           cin >> number;
  12.  
  13.           if ( number == 2 || number == 3 ) // 2 and 3 are always prime numbers
  14.           {
  15.                cout << "this number is prime" << endl;
  16.           }
  17.  
  18.           else if( number % 2 == 0 || number % 3 == 0 ) // if # is divisible by 2 or 3
  19.           {
  20.                cout << "This number is not prime" << endl;
  21.           }
  22.  
  23.           else             
  24.           {
  25.                cout << "This number is prime." << endl;
  26.           }
  27.  
  28.      }        
  29.  
  30.      return 0; 
  31. }
  32.  
  33.  
Nov 12 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.