#include <iostream>
usingnamespace std;
int main()
{
int n, c = 2;
cout<<"Enter a number to check if it is prime\n";
cin>>n;
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 ) //
{
cout<< n <<"is not prime.\n";
break;
}
}
if ( c == n )
cout<< n <<" is prime.\n";
return 0;
}
so lets assume the n value input is 3 here.
for ( c = 2 ; c <= n - 1 ; c++ )
in this statement c value is 2 and the condition is satisfied i.e c<=3-1=2, so it checks IF condition
if ( n%c == 0 )
3%2 == 0 which is not true so it skips for next statement
if ( c == n )
so 2 == 3 .
how can the system say 3 is prime by this condition. sorry for the newbie question.
This means, check if the user input is divisible by c. A prime number is only divisible by 1 and itself, so if it is divisible by some other number then it can't be a prime number.
for ( c = 2 ; c <= n - 1 ; c++ )
This means, start from the number 2, we already know that all numbers are divisible by 1, so we can skip it and start from the next number. We loop through all the numbers from 2 to n-1 which is the range of all the numbers in between 1 and the number entered. Because if any of that is divisible then it's not prime.
if ( c == n )
check to see if c is equal to the number entered, if c is equal to n, that means we've looped through all the numbers within our range, and if we've looped through everything and didn't find any number that is divisible, then the number we have must be divisible only by 1 and itself, which must be a prime number.
Hopefully that helps you understand what's going on now. :)
thx for the explanation but im not able to get the last part if ( c == n ).
lets say c value is 2 from the for loop and 3(n) value is entered so im guessing it first checks 2==3 and 3==3. im really confused dude sorry. :(
#include <iostream>
usingnamespace std;
int main()
{
int n=5, c = 2;
for ( c = 2 ; c <= n-1 ; c++ ) //
{
if ( n%c == 0 ) // 5%3==2
{
cout<< n <<"is not prime.\n";
break;
}
}
if ( c == n ) // (4==5) is not prime :(
cout<< n <<" is prime.\n";
return 0;
}
at 2ndif im getting 4==5, i thought i would get 5==5.