Write a program that reads a positive integer and checks if it is a prime.
#include <stdio.h>
int is_prime(int n) {
int i;
if (n < 2) {
return 0;
}
if (n == 2) {
return 1;
}
i = 3;
while (i*i <= n) {
if (n%i == 0) {
return 0;
}
i += 2;
}
return 1;
}
int main() {
int n;
printf("Enter a positive number: ");
scanf("%d", &n);
if (is_prime(n)) {
printf("The number is prime\n");
}
else {
printf("The number is not prime\n");
}
return 0;
}
Comments
Leave a comment