Well...It looks fairly simple and I could do this myself. But one thing I don't understand is how come doing a prime number test requires assuming a number is true in the very beginning of the main function. Here is an EXAMPLE of the book I bought, and I think it was published and released after 2001, which is a bit old and sounds out-dated. Anyway, here it is:
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
|
#include <isotream>
#include <cmath>
using namespace std;
int main() {
int n; // Number to test for prime-ness
int i; // Loop Counter
int is_prime; // Boolean Flag. For new compiler, it is better to use bool rather than int
// Assuming that a number is prime until proven otherwise
is_prime = true;
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime-ness by checking for divisibility by
// all whole numbers from 2 to sqrt(n)
i = 2;
while (i <= sqrt(static_cast<double>(n)) {
if (n % i == 0)
is_prime = false;
i++;
}
if (is_prime)
cout << "Number is prime.";
else
cout << "Number is not prime.";
}
|
Question 1: Well, when doing the prime test, do we always NEED TO ASSUME the number is TRUE by doing
is_prime = true;
? What's the benefit of doing that?
Question 2: Since stating is_prime is true, that means
is_prime = 1
. So in the if(is_prime) decision making, it will always print the message, "the number is prime." But what about if the number is not prime, and that means it gets the remainder, so how does it print the message? Unless if(is_prime) = 0, the message will never work and this is based on my own understanding. But in logic, it does work. My question is HOW IT WORK, and I need step by step explanation here.
Question 3: Based on my understanding, if_prime = false, which is located in the while loop and if the number is not prime, which means it gets the remainder, when it is done, where is this value stored? since is_prime has been assumed to be true is_prime = true. Isn't there a contradiction true vs false? I am confused at this point as well. Since true has been assigned to if(is_prime), if false is assigned to if(if_prime), that will contradict one another.
Question 4: Instead of placing the assumption at the beginning of the main function, is it possible to place it within the while loop, same as the is_prime = false?
How the whole thing works is still a mystery to me. And the book does not explain this point in real clarity.