Doubt about getting prime numbers 0 to 100

Hello to everyone, I recently started to learn c++ with this book "Jumping into C++" from Alex Allain. In this book there is an example of a program to get the prime numbers from 0 to 100 that Im not understanding!Isnt the program checking in "isDivisible" function if the remainder of two numbers is = 0? Because if its 0 than its a prime! but 10%2 and 10%5 gives 0 as remainder and 10 isnt prime and the program its not putting 10 on the list and it is correct!But Im not understanding how the program is knowing what numbers are prime and what numbers are not.
If someone could explain the steps of this program to me I would be very grateful.

Heres the code:
 ``123456789101112131415161718192021222324`` ``````[output][output]#include // note the use of function prototypes bool isDivisible (int number, int divisor); bool isPrime (int number); using namespace std; int main (){ for ( int i = 0; i < 100; i++ ){ if ( isPrime( i ) ){ cout << i << endl; } } system("pause"); } bool isPrime (int number) { for ( int i = 2; i < number; i++){ if ( isDivisible( number, i ) ){ return false; } } return true; } bool isDivisible (int number, int divisor){ return number % divisor== 0; }``````
Last edited on
A crude method of determining if a number is prime or not is dividing it repeatedly from 2 to its closest neighbor.

For the number 13, this means the program would divide it to:
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

If the remainder of any of these divisions is zero, then the number isn't prime.
This is what the for() loop does in isPrime():
repeatedly divides the `number` it receives to 2, 3, ... number - 1.
It returns false if any division has the remainder zero, or true if none of the divisions were exact.

http://en.wikipedia.org/wiki/Prime_number#Testing_primality_and_integer_factorization
Last edited on
Looks like you need to brush up on your boolean logic.

`isDivisible` returns `true` if number is evenly divisible by divisor. A better name for this function would have been `isEvenlyDivisible`.

At line 16, if a number is evenly divisible by i (divisor), then `false` is returned, meaning the number is not prime. In your example, if number is 10 and i is 2, then isDivisible returns true and isPrime returns false indicating 10 is not prime.

If a number is not evenly divisible by any number less than itself, then true is returned at line 20 indicating the number is prime.
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Hello to both, thankyou for explaining this program to me! I now understood this! I realize that I didnt pay attention to somethings!
Topic archived. No new replies allowed.