A prime number is a natural number greater than 1 which is not divisible by any other smaller natural number. In simple terms a prime number has only two positive divisors 1 and itself for example 2,3,5,7—– are prime numbers. Natural numbers other than prime numbers are known as composite numbers.
C Code for Prime Number
Lets see the C code for prime number. There are many different ways to write a C program to check whether a given number is a prime number or not. The simplest approach for checking prime numbers is to use a loop to iterate through all the numbers from 2 to the square root of the number. If any of those numbers divide the given number then the given number is not a prime number. Otherwise, it is a prime number.
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
else
{
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
}
void main()
{
int number;
printf("enter the number ");
scanf("%d", &number);
if (isPrime(number))
{
printf("Prime number");
}
else
{
printf("Not prime number");
}
}
6 thoughts on “C Code for Prime Number”