Check The Programming Section
A prime number is a number which have only two factors as 1 and the number iteself. For example, 13 is prime number, because it is only divisible by 1 and 13. A non-prime number have more than two factors such as 25 and it is divissible by 1, 5, and 25. 2 is the only even number which is a prime number and 0, 1 is neither prime nor composite. To check a given number we can follow various approaches, as follows:
Start dividing the number from 1 to iteself and use a counter to count once the reminder is zero. Later on we can use the value of count, if it is 2 then number is prime else non-prime.
#include<stdio.h>
void checkPrime(int num){
int count = 0;
if(num==0 || num==1)
printf("%d is neither prime nor composite",num);
else{
for(int i=1;i<=num;i++){
if(num%i==0){
count++;
}
}
}
if(count==2) printf("%d has %d factors and a prime number",num,count);
else printf("%d has %d factors and a non-prime number",num);
}
int main(){
int num;
printf("Enter Any number::");
scanf("%d",&num);
checkPrime(num);
return 0;
}
Another and better approach we can follow, instead of start dividing that number from 1, this process will start from 2 and will continue till the half of that number. In this approach, it is number of iterations will less than the previous approach. Instead of checking a number prime by counting number of factors, we can look for its factors (excluding 1 and itself).
#include<stdio.h>
int checkPrime(int num){
int check = 0;
if(num==0 || num==1){
printf("%d is neither prime nor composite",num);
return 0;
}
else{
for(int i=2;i<=num/2;i++){
if(num%i==0){
check = 1;
break;
}
}
}
if(check==1) printf("%d is a non-prime number",num);
else printf("%d is a prime number",num);
}
int main(){
int num;
printf("Enter Any number::");
scanf("%d",&num);
checkPrime(num);
return 0;
}