In this tutorial we will learn how to write a program that find the given number is prime or not.
The prime number should be divisible by 1 and itself.This is the main concept of this program.
In first output the entered value is 15
After checking
15 is not Prime number because it is divisible by
1, 3, 5, 15
In second output the entered value is 17
After checking
17 is a Prime number because it is divisible by only 17
The prime number should be divisible by 1 and itself.This is the main concept of this program.
C program code
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i,count=0;
printf("\n 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("\n The given number %d is Prime Number\n",num);
}
else
{
printf("\n 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);
}
}
}
getch();
}
OUTPUT 1:
OUTPUT 2:
Explanation:-
- 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 thecount 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 thecount 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 ofnumber(253) the count will getincremented 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); } } }
In first output the entered value is 15
After checking
15 is not Prime number because it is divisible by
1, 3, 5, 15
In second output the entered value is 17
After checking
17 is a Prime number because it is divisible by only 17
Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.
Created by-- HARSH CHAUHAN
No comments:
Post a Comment