A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. To check if a number is prime or not in C, you can use a simple program that iterates through potential divisors and checks if the number is divisible by any of them. Here's a basic C program to determine if a number is prime:
c#include <stdio.h>
int isPrime(int num)
{
if (num <= 1)
{
return 0; // 0 and 1 are not prime numbers
}
for (int i = 2; i * i <= num; i++)
{
if (num % i == 0)
{
return 0; // If num is divisible by any number from 2 to sqrt(num), it's not prime
}
}
return 1; // If no divisors were found, it's a prime number
}
int main()
{
int num;
printf("Enter a positive integer: ");
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;
}
In this program:
The
isPrime
function takes an integernum
as input and returns 1 if it's prime and 0 if it's not.Inside the
isPrime
function:
In the
- If
num
is less than or equal to 1, it immediately returns 0 because 0 and 1 are not prime numbers.- It iterates from 2 to the square root of
num
using afor
loop.- Within the loop, it checks if
num
is divisible by the currenti
. If it is, it returns 0 because a divisor was found.- If no divisors are found in the loop, it returns 1, indicating that
num
is prime.
main
function:- The user is prompted to enter a positive integer.
- The
isPrime
function is called to determine if the input number is prime or not. - The result is printed to the console.
- When you run the program, it will tell you whether the entered number is prime or not
Follow us