![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Dec 2005
Posts: 18
Rep Power: 0
![]() |
prime number, problem
bool isPrime(int num)
{
bool isPrimeNum;
int sqrtNum;
int divisor = 3;
if (num == 2)
isPrimeNum = true;
else
if (num % 2==0)
isPrimeNum=false;
else
{
isPrimeNum = true;
sqrtNum = static_cast<int>(pow(static_cast<double>(num), 0.5));
while (divisor <= num )
{
if (num % divisor == 0 )
{
isPrimeNum = false;
cout << " not prime number"<<endl;
break;
}
else
divisor = divisor + 2;
}
}
return isPrimeNum;
}im going to crack my head because of this program, i failed to solve the problem, i cant print out the " is not prime " message. any idea, guys ? |
|
|
|
|
|
#2 |
|
Newbie
Join Date: May 2006
Posts: 28
Rep Power: 0
![]() |
Is there any reason for the sqrtNum variable, i cant see it doing anything.
|
|
|
|
|
|
#3 |
|
Programmer
Join Date: Apr 2006
Location: Calgary, Alberta
Posts: 67
Rep Power: 3
![]() |
When I ran your code, the cout worked fine.
And your code as of now works backwards. It just thinks primes are not primes, and vise versa. Last edited by Twilight; Jun 2nd, 2006 at 2:47 PM. |
|
|
|
|
|
#4 |
|
Hobbyist Programmer
Join Date: May 2006
Location: West Jordan, Utah, United States
Posts: 176
Rep Power: 3
![]() |
A few things.
in your loop, while ( divisor <= num ) means that if you chose, say 37 and your divisor got to 37, the loop would execute and state that it is not a prime when it is. You need to change `num` to `sqrtNum` or `<=` to `<` If you are testing with even numbers, the cout will never get called: if (num % 2==0) isPrimeNum=false; If you want to make it much more efficient for large numbers, you could compile a list of primes up to 2^16 (by cut and paste/download from the internet) and check against that list up to the square root of the number. It would use more memory, but hardly touch the cpu. If it's not important, this would probably be a waste of time. EDIT: Also try putting your num % xxx in parenthesis(sp?). |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|