Given a positive integer N. The task is to write a C program to check if the number is prime or not.
Definition – A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. (Wikipedia)
Program to check Prime Number
In this program user can check the entered number N is prime or not, where the value of n is input by the user
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
// condition for non-prime
if (n % i == 0) {
flag = 1;
break;
}
}
if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
Program to find first N Prime Numbers
Below is a program to find first n prime numbers using nested for loops, where the value of n is input by the user.
#include<stdio.h>
int main()
{
int n,i = 3, count, c;
printf("nEnter the number of prime numbers required : ");
scanf("%d", &n);
if(n >= 1)
{
printf("nnFirst %d prime numbers are : ", n);
printf("2 ");
}
// iteration for n prime numbers
// i is the number to be checked in each iteration starting from 3
for(count = 2; count <= n; i++)
{
// iteration to check c is prime or not
for(c = 2; c < i; c++)
{
if(i%c == 0)
break;
}
if(c == i) // c is prime
{
printf("%d ", i);
count++; // increment the count of prime numbers
}
}
return 0;
}