Prime Number Program in C | Program for Prime Number in C
Program to check a single number is prime or not in c:
In this program, we will take input from the user and check whether the given input number is prime or not.
Output:

C Program to check given number is prime or not using for loop:
In this program, we will ask the user to input n number and check whether the given n number is prime or not using for loop.
Output:

Explanation:
let us consider n=5 for loop becomes for(i=1; i<5; i++)
1st Iteration: for(i=1; i<=5; i++) in 1st iteration i is incremented i.e the value of i for the next iteration is 2.If (n%i==0) then c is incremented i.e (5%1==0) then c is incremented.Here, (5%1=0) so c is incremented i.e c=1.
2nd Iteration: for(i=2;i<=5;i++) in 2nd iteration i is incremented i.e the value of i for the next iteration is 3.If (n%i==0) then c is incremented i.e (5%2==0) then c is incremented.here,(5%2!=0) so c is not incremented i.e c=1.
3rd Iteration: for(i=3;i<=5;i++) in 3nd iteration i is incremented i.e the value of i for the next iteration is 4.If (n%i==0) then c is incremented i.e (5%3==0) then c is incremented.Here,(5%3!=0) so c is not incremented i.e c=1.
4th Iteration: for(i=4;i<=5;i++) in 4th iteration i is incremented i.e the value of i for the next iteration is 5.If (n%i==0) then c is incremented i.e (5%4==0) then c is incremented.Here,(5%4!=0) so c is not incremented i.e c=1.
5th Iteration: for(i=5;i<=5;i++) in 5th iteration i is incremented i.e the value of i for the next iteration is 6.If (n%i==0) then c is incremented i.e (5%5==1) then c is incremented.Here,(5%5=0) so c is incremented i.e c=2.
6th Iteration: for(i=6;i<=5;i++) in 6th iteration the value of i is 6 which is greater than n i.e i>n(6>5) so the for loop is terminated.Here c=2 so the given number is prime number.
C Program to check given number is prime or not using while loop:
In this program we will ask user to enter the number which user want to check whether it is prime or not and then check it using while loop.
Output:

In above program we just replace the for loop instead we add while loop.
C program to check the given number is prime or not using functions:
In this program, we will use the function find_factors to check whether the given number is prime or not.
Output:

Sieve Of Eratosthenes Algorithm:
In this algorithm, we first declare the numbers from [2:n]. We mark all the multiples of 2 as the number 2 is composite. A proper multiple of number x, which is multiple of number x and divisible by x.
Then we mark the number which hasn’t be composite.for example 3 which is not composite,It means that 3 is a prime number.
Now we will see the program for Sieve Of Eratosthenes Algorithm.
Here we have a program that counts the no of primes smaller than or equal to n.
Post a Comment