Write a C, C++ program to print prime number from 1 to n or 1 to 100. How to generate prime numbers between 1 to n.

This type of questions are mostly asked during viva or in interviews.

To solve this problem you can either use brute-force approach or you can use most efficient Sieve of Eratosthenes algorithm for generating prime number.

In this post, I'll show how to generate prime numbers using Sieve of Eratosthenes Algorithm.

Interview Questions.

Program to check whether entered number is prime or not .

Let's first understand how this algorithm works. Suppose we have to find prime numbers between 2 to 15.

2 3 4 5 6 7 8 9 10 11 12 13 14 15

2 3~~4~~ 5 ~~6~~ 7 ~~8~~ 9 ~~10~~ 11 ~~12~~ 13 ~~14~~ 15

2 3~~4~~ 5 ~~6~~ 7 ~~8~~ ~~9~~ ~~10~~ 11 ~~12~~ 13 ~~14~~ ~~15~~

So at the end the element which is left is prime numbers.

So the prime numbers between 1 to 15 is

This type of questions are mostly asked during viva or in interviews.

To solve this problem you can either use brute-force approach or you can use most efficient Sieve of Eratosthenes algorithm for generating prime number.

In this post, I'll show how to generate prime numbers using Sieve of Eratosthenes Algorithm.

Interview Questions.

Program to check whether entered number is prime or not .

Let's first understand how this algorithm works. Suppose we have to find prime numbers between 2 to 15.

**Step 1**: Generate number from 2 to 15.2 3 4 5 6 7 8 9 10 11 12 13 14 15

**Step 2**: 2 is the first element in the list. Strike out it's multiple.2 3

**Step 3:**3 is the next element in the list. Strike out it's multiple.2 3

So at the end the element which is left is prime numbers.

So the prime numbers between 1 to 15 is

**2 3 5 7 11 13**

## Program to Print Prime Numbers between 1 to 100

#include <stdio.h> int main() { int num,i,prime[100],k=2; printf("Enter number (less than or equal to 100) \n"); scanf("%d",&num); /*Generate number 1 to n and marked as zero. */ for(i=2;i<=num;i++){ prime[i]=0; } while(k<num){ /* Marked multiple of number as 1.*/ for(i=2;num>=k*i;i++){ prime[k*i]=1; } k++; } for(i=2;i<=num;i++){ /* Number marked left as zero is a prime number.*/ if(prime[i]==0){ printf("%d\n",i); } } return 0; }

## No comments:

## Post a Comment