Okay so first off, maths...
Lines 14-16, you state that if n (the number) equals two, then it is not a prime. Two (2) though is a prime number. A prime number is divisible only by two numbers, itself and one. Two fits this mold and is therefore a prime number.
So far we have dealt with many numbers you could run across. All negative numbers, one and 2 have been dealt with in your code. This is good. You're on the right track.
Now what is another thing we know about prime numbers? Well above two prime numbers cannot be even. Right? In proofs, a generic (i.e. non-specified/could be any) even number is represented as "2*k" where k is some value. So we know right off the bat, any even number larger than 2 can be, and is, expressed as a multiple of 2.
This means we can get rid of ALL even numbers larger than two because we already know that they cannot be prime.
How would we do this? (Hint hint... use '%').
Okay so negatives, zero, 1, 2, and all even numbers are dealt with, no need to worry about them, your code will handle them now.
Part (I don't know, let's say 3) PART THREE!
All we need to do after we have done what I have previously said is add in a small while loop and and if statement.
You will have a while loop, which checks whether your divisor is greater than your number.
Inside of this you will use the modulus (%) operator again to check for whether the number modulus of your divisor equals 0, if it does. That means that your number is NOT a prime.
1 2 3 4 5 6 7 8 9 10 11
|
bool prime = true; //Assume it is true and have the code dictate if it is or is not true
int divisor = 3; //This is because negatives, 0, 1, and 2 are accounted for.
double num_d = static_cast<double>(num);
int upperLimit = static_cast<int>(sqrt(num_d) +1);
while (divisor <= upperLimit)
{
if (num % divisor == 0) //If this is 0, that number divided with no remainder.
prime = false;
divisor +=2; //+2 because we excluded all even numbers.
}
|
Code credit goes to Grey Wolf for actual code:
http://www.cplusplus.com/forum/general/1125/