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.
[output][output]#include <iostream>
// note the use of function prototypes
bool isDivisible (int number, int divisor);
bool isPrime (int number);
usingnamespace 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 ) ){
returnfalse;
}
}
returntrue;
}
bool isDivisible (int number, int divisor){
return number % divisor== 0;
}
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.
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.