This is a approach for Weather a number is prime or not
QUESTION:
int main()
{
int i, num, b;
printf("ENTER A NUMBER : \n");
scanf("%d", &num);
for (i = 2; i <= num - 1; i )
{
if (num % i == 0)
break;
}
if (i == num)
printf("PRIME");
else
printf("NOT A PRIME");
return 0;
}
How will the value of i
will be incremented if loop is completed..The condition for stopping is num-1 then how in next statement value of i will be == num
Ex: if i enter 5 loop will run till 4 and value of i will be 4 then how will it will be == num..
Hope question is understood.
CodePudding user response:
The body of the for
loop is executed as long as the test condition is true. That means, when the loop stops executing because of the test condition (rather than because of the break
), the test condition is false.
Therefore, when the loop ends this way, i <= num - 1
is false. Since num
is 5, that means i <= 4
is false, which occurs when i
has become 5.
CodePudding user response:
I got your point , Let's analyze it together First let's be clear about prime numbers A prime number is a number that is only divisible by itself and one so , if we iterate from 2 till the number - 1 we are including all the numbers in range 2 & number-1 and in case any of those numbers are divisible by our variable then it's not a prime and we break the loop before it reaches number-1
I see you're confused in the stopping condition the stopping condition is number! the loop is valid till number -1 then it increments so i will be equal to the number and the condition of the loop is not satisfied in this case we can say that we reached all numbers between 2 and number -1 and found nothing divisible by our variable hence it's prime else if the counter i didn't reach the number itself this means that the loop went into a break and a break means we found a divisible integer so it's not prime Hope this helped!