Examples of C part 22 check prime number or not
#include<stdio.h> main() { int num,i,count=0; printf("Enter a number to check whether it is prime or not\n"); scanf("%d",&num); for(i=1;i<=num;i++) { if(num%i==0) { count++; } } if(count==2) { printf("The given number %d is Prime Number\n",num); } else { printf("The given number %d is not Prime Number\n because The number is divisible by\n",num); for(i=1;i<=num;i++) { if(num%i==0) { printf("%d\n",i); } } } }
Enter a number to check whether it is prime or not
27
The given number 27 is not Prime Number
because The number is divisible by
1
3
9
27Explanation:
The prime number should be divisible by 1 and itself.This is the main concept of this program.
- The program starts with initializing
- num → To store number
- i → Temporary variable
- count → To store number of divisors
printf("Enter a number to check whether it is prime or not\n"); scanf("%d",&num);
for(i=1;i<=num;i++) { if(num%i==0) { count++; } }
- Iteration 1:i=1,i less than 253
- In if num%i==0 → 253%1==0 which is true
- Then count increments by 1.So count=1;
- Iteration 2:i=2,i less than 253
- In if num%i==0 → 253%2==0 which is false
- As the condition is false the count remains same so count is still count=1
- Iteration 3:i=3,i less than 253
- In if num%i==0 → 253%3==0 which is false
- As the condition is false the count remains same so count is still count=1
- Like this it goes on till iteration 11
- ...........
- Iteration 11:i=11,i less than 253
- In if num%i==0 → 253%11==0 which is true
- Then count increments by 1.So count=2;
- Like this for every divisor of number(253) the count will get incremented and in this case of number(253) there are 4 divisors (they are:1,11,13,153) until i=253
- So the count=4
- Iteration 1:i=1,i less than 253
if(count==2) { printf("The given number %d is Prime Number\n",num); } else { printf("The given number %d is not Prime Number\n because The number is divisible by\n",num); for(i=1;i<=num;i++) { if(num%i==0) { printf("%d\n",i); } } }