Prime Numbers using Sieve of Eratosthenes: C Program

Implement in a c program the following procedure to generate prime numbers from 1 to 100. This procedure is called Sieve of Eratosthenes.

Step 1: Fill an array num[100] with numbers from 1 to 100.

Step 2: Starting with the second entry in the array, set all its multiples to zero.

Step 3: Proceed to the next non-zero element and set all its multiples to zero.

Step 4: Repeat Step 3 till you have set up the multiples of all the non-zero elements to zero.

Step 5: At the conclusion of Step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.

Simpler Version of Sieve of Eratosthenes

You can watch our previous video tutorial for simpler version of Sieve of Eratosthenes method to find prime numbers from 2 to N: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program.

Visual Representation

prime numbers from 2 to 100 sieve of erathosthenes

Video Tutorial: Prime Numbers using Sieve of Eratosthenes: C Program


[youtube https://www.youtube.com/watch?v=oL9jzKm6uZQ]

YouTube Link: https://www.youtube.com/watch?v=oL9jzKm6uZQ [Watch the Video In Full Screen.]

Input num[N] with numbers 1 to 100

Step 1:

#include<stdio.h>

#define N 100

int main()
{
    int num[N], i;

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 0; i < N; i++)
            printf("%d\t", num[i]);

    return 0;
}

Output:
This code outputs natural numbers from 1 to 100.

Note:
Array index starts from 0. So elements from index 0 to 99 will have 100 elements.

At index 0 we’ll store number 1, and at index 1 we’ll store number 2 and so on until index 99 where we store number 100. i.e., the index number is 1 less than the element/number present at that index.

Starting with the second entry in the array, set all its multiples to zero.

Step 2:

    int limit = sqrt(N);

    for(i = 1; i <= limit; i++)
    {
        if(num[i] != 0)
        {
            for(j = pow(num[i], 2); j <= N; j = j + num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

Here we initialize i to second entry in the array, which has element 2(first prime number). Iterate the for loop until i is less than or equal to square root of N or you can even write (num[i] * num[i]) <= N as the condition for outer for loop. We’ve shown the reason for writing that condition in our other video tutorial present here: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program.

Step 3: Proceed to the next non-zero element and set all its multiples to zero.

Inside inner for loop: for any non-zero element we check for their multiples and if we find any, we store 0 – indicating that it was a composite number.

We repeat Step 3 till we have set up the multiples of all the non-zero elements to zero.

Initialized j to pow(num[i], 2) ?

Because the first number to be struck off by num[i] will be pow(num[i], 2) or (num[i] x num[i]). In other words, the first number or the first multiple of num[i] where our program will insert 0 is pow(num[i], 2) or (num[i] x num[i]).

j = j + num[i]
It can also be written as j += num[i]. For each iteration of inner for loop, j value should increment by num[i] times, so that the position (j – 1) will have the multiple of number present at num[i]. In that case num[j – 1] will be multiple of num[i], and hence composite number – so we store 0 at num[j – 1].

Step 5: Print Prime Numbers
Finally all the non-zero numbers/elements are prime numbers.

Source Code: Prime Numbers using Sieve of Eratosthenes: C Program

using math.h library file

#include<stdio.h>
#include<math.h>

#define N 100

int main()
{
    int num[N], i, j;
    int limit = sqrt(N);

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 1; i <= limit; i++)
    {
        if(num[i] != 0)
        {
            for(j = pow(num[i], 2); j <= N; j = j + num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

    printf("Sieve of Eratosthenes Method\n");
    printf("To find Prime numbers from 2 to %d\n\n", N);
    for(i = 1; i < N; i++)
    {
        if(num[i] != 0)
            printf("%d\t", num[i]);
    }

    printf("\n");

    return 0;
}

Output
This outputs all the prime numbers from 2 to 100.

Source Code: Without using math.h library file

#include<stdio.h>

#define N 100

int main()
{
    int num[N], i, j;

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 1; (num[i] * num[i]) <= N; i++)
    {
        if(num[i] != 0)
        {
            for(j = num[i] * num[i]; j <= N; j += num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

    printf("Sieve of Eratosthenes Method\n");
    printf("To find Prime numbers from 2 to %d\n\n", N);
    for(i = 1; i < N; i++)
    {
        if(num[i] != 0)
            printf("%d\t", num[i]);
    }

    printf("\n");

    return 0;
}

Output
This outputs all the prime numbers from 2 to 100.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Count Prime Numbers Between Range

Lets write a C program to count prime numbers between user entered/input range of numbers, using function/method.

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Related Read:
C Program To Find Prime Number or Not using For Loop

Video Tutorial: C Program To Count Prime Numbers Between Range


[youtube https://www.youtube.com/watch?v=vY6HFMblBJY]

YouTube Link: https://www.youtube.com/watch?v=vY6HFMblBJY [Watch the Video In Full Screen.]

Source Code: C Program To Count Prime Numbers Between Range

#include<stdio.h>
#include<math.h>

int isPrime(int num)
{
    int inum = sqrt(num), prime = 1, count;

    for(count = 2; count <= inum; count++)
    {
         if(num % count == 0)
         {
            prime = 0;
            break;
         }
    }

    return(prime);
}

int main()
{
    int start, end, temp, num, slno = 0, on_off;

    printf("Enter start and end value\n");
    scanf("%d%d", &start, &end);

    printf("Do you want to print prime numbers? (yes = 1, no = 0)\n");
    scanf("%d", &on_off);

    if(start > end)
    {
        temp  = start;
        start = end;
        end   = temp;
    }

    if(on_off)
        printf("\nPrime numbers between %d and %d are:\n\n", start, end);

    for(num = start; num <= end; num++)
    {
        if(num == 1)
        {
            continue;
        }

        if( isPrime(num) )
        {
            slno++;

            if(on_off)
            {
                printf("%d. %d is prime number.\n", slno, num);
            }
         }
    }

    printf("\nThere are %d prime numbers between %d and %d.\n", 
             slno, start, end);

    return 0;
}

Output 1:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 10 and 30 are:

1. 11 is prime number.
2. 13 is prime number.
3. 17 is prime number.
4. 19 is prime number.
5. 23 is prime number.
6. 29 is prime number.

There are 6 prime numbers between 10 and 30.

Output 2:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 6 prime numbers between 10 and 30.

Output 3:
Enter start and end value
1
10
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 1 and 10 are:

1. 2 is prime number.
2. 3 is prime number.
3. 5 is prime number.
4. 7 is prime number.

There are 4 prime numbers between 1 and 10.

Output 4:
Enter start and end value
1
300
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 62 prime numbers between 1 and 300.

Output 5:
Enter start and end value
1
1000
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 168 prime numbers between 1 and 1000.

Logic To Count Prime Numbers Between Range

First we ask the user to enter the range and store it inside address of variables start and end. We make sure that start value is less than end value. If start value is greater than end value, we use a temporary variable to swap the values of start and end.

Swap 2 Numbers Using a Temporary Variable: C

Next we ask the user if he / she wants to display the prime numbers between the range or just want to know the count of prime numbers between the entered range. We store the user answer in a variable called on_off.

We start the for loop: We initialize the loop counter variable num to start and iterate through the loop until num is less than or equal to end. For each iteration of the for loop we increment the value of num by 1. This for loop selects number one by one from start to end. And this selected number, which is present inside variable num is checked for prime or not. If its prime we display it to the console window and keep track of the count of prime numbers, if not we simply ignore that non-prime number.

We use a function to check if the selected number present in variable num is a prime number or not. We call the function/method isPrime() inside if condition and pass the value of num to it. isPrime() returns 1 or 0 value. 1 means true and 0 means false. So if isPrime() returns 1, then the if condition becomes true and we increment the value of slno by 1 and optionally printout the prime number. If isPrime() returns 0, then we simply ignore it and go to the next number.

isPrime() function has the logic to determine if the given number is prime or not. We have explained the complete logic of this in a separate video tutorial, link to which is present below.

C Program To Find Prime Number or Not using For Loop

Note:
1. We are including math.h header file or library file since we are using sqrt() builtin method. sqrt() method is present inside math.h file.

2. We are also using continue and break keywords in our program and we’ve explained about it in detail in separate videos. Please watch them for more clarity about the topic.

Continue Statement In C Programming Language
break Statement In C Programming Language

Stay subscribed to our blog and YouTube channel. Thank you ..

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Print N Co-Prime Numbers

Lets write a C program to print N co-prime or relative prime numbers. N being the user entered limit for printing the co-prime number pairs.

Co-Prime numbers / Relative Prime Numbers: Two numbers are said to be co-prime or relative prime numbers if they do not have a common factor other than 1.

OR

Two numbers whose Greatest Common Divisor(GCD) is 1 are known as Co-Prime or Relative Prime Numbers.

Note: User entered numbers(to check for co-prime) do not require to be prime numbers.

Related Read:
C Program to Find Factors of a Number using For Loop

Factors of a number: All the numbers which perfectly divide a given number are called as Factors of that number.

Expected Result

If user inputs limit = 5
Output
1. ( 2, 3 ) are co-prime numbers.
2. ( 3, 4 ) are co-prime numbers.
3. ( 2, 5 ) are co-prime numbers.
4. ( 3, 5 ) are co-prime numbers.
5. ( 4, 5 ) are co-prime numbers.

Logic To Find If Two Numbers are Co-Prime or Not

Entire logic is present in our previous video tutorial. Please visit the link and watch the video without fail before going further: C Program To Find Two Numbers are Co-Prime or Not

Video Tutorial: C Program To Print N Co-Prime Numbers


[youtube https://www.youtube.com/watch?v=EnXhsLgFlAQ]

YouTube Link: https://www.youtube.com/watch?v=EnXhsLgFlAQ [Watch the Video In Full Screen.]

Source Code: C Program To Print N Co-Prime Numbers

#include<stdio.h>

int main()
{
    int limit, num1, num2 = 3, count, flag, slno = 1;

    printf("How many co-prime numbers you want to print?\n");
    scanf("%d", &limit);

    while(limit)
    {

        for(num1 = 2; num1 <= num2; num1++)
        {
            for(count = 2; count <= num1; count++)
            {
                flag = 1;
                if(num1 % count == 0 && num2 % count == 0)
                {
                    flag = 0;
                    break;
                }
            }

            if(flag)
            {
                printf("%d. (%d, %d) are co-prime numbers.\n", 
                      slno++, num1, num2);
                limit--;

                if(limit == 0)
                {
                    num1 = num2 + 10;
                }
            }

        }

        num2++;
    }

    return 0;
}

Output 1:
How many co-prime numbers you want to print?
10
1. ( 2, 3 ) are co-prime numbers.
2. ( 3, 4 ) are co-prime numbers.
3. ( 2, 5 ) are co-prime numbers.
4. ( 3, 5 ) are co-prime numbers.
5. ( 4, 5 ) are co-prime numbers.
6. ( 5, 6 ) are co-prime numbers.
7. ( 2, 7 ) are co-prime numbers.
8. ( 3, 7 ) are co-prime numbers.
9. ( 4, 7 ) are co-prime numbers.
10. ( 5, 7 ) are co-prime numbers.

Output 2:
How many co-prime numbers you want to print?
14
1. ( 2, 3 ) are co-prime numbers.
2. ( 3, 4 ) are co-prime numbers.
3. ( 2, 5 ) are co-prime numbers.
4. ( 3, 5 ) are co-prime numbers.
5. ( 4, 5 ) are co-prime numbers.
6. ( 5, 6 ) are co-prime numbers.
7. ( 2, 7 ) are co-prime numbers.
8. ( 3, 7 ) are co-prime numbers.
9. ( 4, 7 ) are co-prime numbers.
10. ( 5, 7 ) are co-prime numbers.
11. ( 6, 7 ) are co-prime numbers.
12. ( 3, 8 ) are co-prime numbers.
13. ( 5, 8 ) are co-prime numbers.
14. ( 7, 8 ) are co-prime numbers.

Logic To Print N Co-Prime Numbers

User enters limit value i.e., how many co-prime numbers he or she wants to print. We put that limit inside while loop condition. So while loop code executes repeatedly until limit is not equal to 0. We decrement the value of limit by 1 as and when we print the co-prime numbers.

Inside while loop we write nested for loop. The outer for loop selects the values for num1 and num2. We know that the first co-prime or relative prime number is 2 and 3. So we initialize num1 = 2 and num2 = 3. We keep incrementing the value of num2 by one outside the outer for loop, and iterate the for loop until num1 is less than or equal to num2.

If num2 is 3, then for loop checks for (num1 always starts from 2, till num1 <= num2) – (2, 2), (3, 2).

Next num2 will be 4. So for loop checks for – (2, 4), (3, 4), (4, 4)

Next num2 will be 5. So for loop checks for – (2, 5), (3, 5), (3, 5), (4, 5) ..and so on.

Inside inner for loop we check if the selected numbers present in num1 and num2 are co-prime or not. That logic is present at C Program To Find Two Numbers are Co-Prime or Not.

Note: Since limit– is inside a for loop, even though limit becomes 0 the while loop won’t exit immediately, until the for loop completes its iterations. It avoid that, we make sure the value of num1 is assigned number greater than num2. That way control exits for loop. Since limit is 0, the control even exits while loop.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find If Two Numbers are Co-Prime or Not using Function

Lets write a C program to check whether two positive numbers entered by the user are Co-Prime numbers / Relative Prime Numbers or not using function / method.

Co-Prime numbers / Relative Prime Numbers: Two numbers are said to be co-prime or relative prime numbers if they do not have a common factor other than 1.

OR

Two numbers whose Greatest Common Divisor(GCD) is 1 are known as Co-Prime or Relative Prime Numbers.

Factors of a number: All the numbers which perfectly divide a given number are called as Factors of that number.

Note: User entered numbers(to check for co-prime) do not require to be prime numbers.

Logic To Find If Two Numbers are Co-Prime or Not

Complete logic is present in our previous day video tutorial, please watch it before continuing: C Program To Find Two Numbers are Co-Prime or Not

Related Read:
C Program To Find Prime Number or Not using While Loop
C Program to Find Factors of a Number using For Loop
Biggest of Two Numbers Using Ternary Operator: C
C Program to Find GCD or HCF of Two Numbers

Video Tutorial: C Program To Find If Two Numbers are Co-Prime or Not using Function


[youtube https://www.youtube.com/watch?v=e_ZRmnrSVhA]

YouTube Link: https://www.youtube.com/watch?v=e_ZRmnrSVhA [Watch the Video In Full Screen.]

Source Code: C Program To Find If Two Numbers are Co-Prime or Not using Function

#include<stdio.h>

int coprime(int num1, int num2)
{
    int min, count, flag = 1;

    min = num1 < num2 ? num1 : num2;

    for(count = 2; count <= min; count++)
    {
        if( num1 % count == 0 && num2 % count == 0 )
        {
            flag = 0;
            break;
        }
    }

    return(flag);
}

int main()
{
    int n1, n2;

    printf("Enter 2 positive numbers\n");
    scanf("%d%d", &n1, &n2);

    if( coprime(n1, n2) )
    {
        printf("%d and %d are co-prime numbers.\n", n1, n2);
    }
    else
    {
        printf("%d and %d are not co-prime numbers.\n", n1, n2);
    }

    return 0;
}

Output 1:
Enter 2 positive numbers
8
15
8 and 15 are co-prime numbers.

Output 2:
Enter 2 positive numbers
12
15
12 and 15 are not co-prime numbers.

Note:
coprime() method returns 1 or 0 value. If it returns 1, then the code inside if block gets executed. If it returns 0, then the code inside else block gets executed.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Two Numbers are Co-Prime or Not

Lets write a C program to check whether two positive numbers entered by the user are Co-Prime numbers / Relative Prime Numbers or not.

Co-Prime numbers / Relative Prime Numbers: Two numbers are said to be co-prime or relative prime numbers if they do not have a common factor other than 1.

OR

Two numbers whose Greatest Common Divisor(GCD) is 1 are known as Co-Prime or Relative Prime Numbers.

Note: User entered numbers(to check for co-prime) do not require to be prime numbers.

Related Read:
C Program To Find Prime Number or Not using While Loop
C Program to Find Factors of a Number using For Loop

Prime Number: Any natural number which is greater than 1 and has only two factors i.e., 1 and the number itself is called a prime number.

Factors of a number: All the numbers which perfectly divide a given number are called as Factors of that number.

Logic To Find If Two Numbers are Co-Prime or Not

If user enters n1 = 8 and n2 = 15;

We find smallest number in these two numbers(8 and 15) and store it inside variable min. So min = 8;

n1 = 8;
n2 = 15;

1st Iteration
count = 2;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 2 == 0 && 15 % 2 == 0 )
( true && false ) = false;

2nd Iteration
count = 3;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 3 == 0 && 15 % 3 == 0 )
( false && true ) = false;

3rd Iteration
count = 4;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 4 == 0 && 15 % 4 == 0 )
( true && false ) = false;

4th Iteration
count = 5;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 5 == 0 && 15 % 5 == 0 )
( false && true ) = false;

5th Iteration
count = 6;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 6 == 0 && 15 % 6 == 0 )
( false && false ) = false;

6th Iteration
count = 7;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 7 == 0 && 15 % 7 == 0 )
( false && false ) = false;

7th Iteration
count = 8;

( n1 % count == 0 && n2 % count == 0 )
( 8 % 8 == 0 && 15 % 8 == 0 )
( true && false ) = false;

Exit For Loop
Since count = 8 and min = 8, control exits for loop.

We’ve checked the complete iteration of for loop and we can see that no common number perfectly divides both user entered numbers n1 and n2 i.e., 8 and 15. So (8, 15) are co-prime numbers or relative prime numbers.

Example for non co-prime number

If n1 = 12 and n2 = 15

Number 3 perfectly divides both n1 and n2 i.e., 12 and 15. So 12 and 15 have 2 common factors i.e., 1 and 3, hence (12, 15) are not co-prime or relative prime numbers.

Video Tutorial: C Program To Check If Two Numbers are Co-Prime or Not


[youtube https://www.youtube.com/watch?v=xjHcwfQRvF4]

YouTube Link: https://www.youtube.com/watch?v=xjHcwfQRvF4 [Watch the Video In Full Screen.]

Source Code: C Program To Find Two Numbers are Co-Prime or Not

#include<stdio.h>

int main()
{
    int n1, n2, min, count, flag = 1;

    printf("Enter 2 positive numbers\n");
    scanf("%d%d", &n1, &n2);

    min = n1 < n2 ? n1 : n2;

    for(count = 2; count <= min; count++)
    {
        if( n1 % count == 0 && n2 % count == 0 )
        {
            flag = 0;
            break;
        }
    }

    if(flag)
    {
        printf("%d and %d are co-prime\n", n1, n2);
    }
    else
    {
        printf("%d and %d are not co-prime\n", n1, n2);
    }

    return 0;
}

Output 1:
Enter 2 positive numbers
8
15
8 and 15 are co-prime

Output 2:
Enter 2 positive numbers
12
15
12 and 15 are not co-prime

Logic To Check If Two Numbers are Co-Prime or Not

User enters 2 positive numbers, we store those numbers in variables n1 and n2 respectively. We find the smallest number in it and store it inside variable min.

We initialize loop counter variable count to 2(as all the numbers are perfectly divisible by 1, so we skip number 1 and start with number 2). We iterate through the for loop until count value is less than or equal to min. We increment the value of count by one for each iteration of for loop.

Inside for loop we check if there are any common factors for n1 and n2.
n1 % count == 0 && n2 % count == 0
If there are any common factors, then those numbers entered by the user are not co-prime / relative prime numbers. If there are no common factors for those two numbers, then they are co-prime or relative prime numbers.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert