Hey all,
I've been reading C++ Without Fear, which in my opinion is a fantastic book for beginners. However, there's an example in the book teaching about detecting prime numbers from user input but I'm not too sure how it's doing certain things. This is a bit odd I know, but I have a very technical mind and I need to understand the 'mechanics' of what I'm doing in order to learn it.
Please note that I did title the variables but that's only because I am having difficulty grasping this and I was trying to make it easier for myself to follow. So I apologize in advance for this.
here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <cmath> // Original preprocessor in book was <math.h>
using namespace std;
int main()
{
int numberProvidedByUser;
int KeyPrimeNumber;
int is_prime;
is_prime = true;
cout <<" Enter number and press ENTER..." <<endl;
cin >> numberProvidedByUser;
KeyPrimeNumber = 2;
while(KeyPrimeNumber <= sqrt((static_cast<double>(numberProvidedByUser)))) {
if(numberProvidedByUser % KeyPrimeNumber == 0) // Determine if number is evenly divided.
is_prime = false;
KeyPrimeNumber++;
}
if(is_prime){
cout << " Number is prime..." << endl;
}else{
cout << " Number is not prime. " <<endl;
}
return 0;
}
|
Ok, now the part I'm having difficulty understanding is this:
1 2 3 4 5 6 7 8 9
|
KeyPrimeNumber = 2;
while(KeyPrimeNumber <= sqrt((static_cast<double>(numberProvidedByUser)))) {
if(numberProvidedByUser % KeyPrimeNumber == 0)
is_prime = false;
KeyPrimeNumber++;
}
|
1. Since 2 is the key prime number, which is just basic math, then how does the loop work when someone enters 1 as the input? Though I realize 1 is considered a 'unit' rather than a 'prime' due to factoring issues it's still technically a prime due to the rule of only-self-and-one-division however, regardless of that, the loop shouldn't run because the square root of 1 is 1 and 2 is not less than or equal to 1. So how is the program 'skipping' the while condition and running anyway?
2. What exactly is KeyPrimeNumber++ doing? I understand that it is incrementing the KeyPrimeNumber value by 1, but why? The loop only runs once so why the incrementation? If I'm understanding the method of incrementation, this is only being done at the end of this code block and therefor if the loop was to 'run again' on it's own, the new KeyPrimeNumber would be 3, 4, 5, respectively with each new loop. This isn't making sense to me and I was hoping someone would explain how this code is working in simple terms.
Thanks all.