bool isPrime(int x = 0)
{
/* Without extra 'count' variable */
//! corner case: 0 and 1 aren't prime numbers
if (x == 0 || x == 1)
return 0;
for (int i = 2; i <= x / 2; i++)
{
if (x > 2 && x % i == 0)
return 0;
}
return 1;
}
#include<stdio.h>
void main()
{
int num;
int prime = 1;
printf("Enter a number = ");
scanf("%d",&num);
for(int i = 2; i < num; i++)
{
if(num % i == 0)
{
prime = 0;
break;
}
}
if(prime == 1 && num>0 && num !=1)
printf("%d is a prime number.", num);
else
printf("%d isn't a prime number.", num);
}
#include <stdio.h>
main() {
int n, i, c = 0;
printf("Enter any number n:");
scanf("%d", &n);
//logic
for (i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
}
}
if (c == 2) {
printf("n is a Prime number");
}
else {
printf("n is not a Prime number");
}
return 0;
}
Program Output:
#include<stdio.h>
void main(){
int num, i;
int cp = 1;
printf("Enter a number = ");
scanf("%d",&num);
if(num > 0){
for(i = 2; i < num; i++){
if(num % i == 0){
cp = 0;
}
}
if(cp == 1){
printf("%d is a prime number.", num);
}
else{
printf("%d isn't a prime number.", num);
}
}
}
int isPrime(int n) {
for (int i = 2; i < n; i++) if (n % i == 0) return 0;
return 1;
}
#include<stdio.h>
int main(){
int n,i,m=0,flag=0;
printf("Enter the number to check prime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Number is not prime");
flag=1;
break;
}
}
if(flag==0)
printf("Number is prime");
return 0;
}