prime chec kin c
To check if a number is prime in C, you can use the following code snippet:
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
This code defines a function isPrime
that takes an integer num
as input and returns 1 if the number is prime, and 0 otherwise. The main
function prompts the user to enter a number, calls the isPrime
function, and prints the result.
The isPrime
function uses a simple algorithm to check if a number is prime. It first checks if the number is less than or equal to 1, in which case it returns 0 (not prime). Then, it iterates from 2 to the square root of the number. If any of these numbers divides the input number evenly (i.e., the remainder is 0), the function returns 0. If no such number is found, the function returns 1, indicating that the number is prime.
To use this code, simply copy it into a C file and compile/run it. You can then enter any number to check if it is prime or not.