C Program To Find Prime Number or Not
#include<stdio.h> #include<conio.h> void main() { int n,i; clrscr(); printf("\n Enter Any Number : "); scanf("%d",&n); for(i=2;i<=n-1;i++) { if(n%i==0) { break; } } if(n==i) printf("\n Prime Number"); else printf("\n Not Prime Number"); getch(); }
Output :
In the above program what we do is,
- we get a number from the user.
- Start a loop which divides the entered number by 2,3,4... and so on until the number one less than the entered number.(since any number is completely divisible by 1 we start the loop from 2)
- Here is the tricky part.
If the entered number isn't completely divisible by any of the number(which suggest the number is prime), that means the loop will run until the number one less than the entered number and value of 'i' will be equal to the entered number in the end. i.e(n==i) - Otherwise the number will be not prime.
However, this method is not so efficient when finding any bigger number such as 500 or 1000. As in that case, the loop has to run 499 and 999 times respectively.
One way mentioned in the video below can be more effective to find the given number is a prime number or not.
Also Check: C Program to Find Prime Numbers in A Given Range
C Program To Find The Prime Number Or Not Using The Function
#include<stdio.h> #include<conio.h> int prime(int m); void main() { int n; clrscr(); printf("\n Enter Any Number : "); scanf("%d",&n); prime(n); getch(); } int prime(int m) { int i,temp; for(i=2;i<=m/2;i++) { if(m%i==0) { temp=0; break; } else temp=1; } if(temp) printf("\n Prime Number"); else printf("\n Not Prime Number"); return 0; }
In this way we, we can find a number is prime or not using this simple method.