Write a C language program that prints out all of the prime numbers in the range
ID: 3562402 • Letter: W
Question
Write a C language program that prints out all of the prime numbers in the range [ 2.. n]. Your program will accept a single command line argument, the integer value n which represents the end of the range. Your program will use the Sieve of Eratosthenes method for finding prime numbers. This method may be described as follows: First, create a list of numbers 2 .. n. Let n = 15 as an example: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Since 2 is prime, we flag all multiples of 2. (If it's a multiple of 2, it can't be prime.) 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Now we proceed to the next item in the list that it unmarked. It will be prime. We mark all multiples of the next prime in the list. In this case, it is 3, so we mark 6, 9, 12, 15. (6 and 12 are already marked). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 We now proceed to the next unmarked number, which is prime. We proceed to 5, and we mark 10 and 15 (already marked). The next number is 7, and we mark 14 (already marked). At this point we can stop. That's because 2 * (any number > 7) is larger than n. (See if you can find a better stopping point). Now, the unmarked elements are the prime numbers. We have 2,3,5,7,11,13. Output example: p2 59 Prime numbers in the range 2..59 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 program should be organized-modularized-into functions. program should be as efficient as possible. program must validate input. If the user types anything other than a single command line argument that is a valid integer, you should print an error message and terminate the program.Explanation / Answer
#include<stdio.h>
void Eratosthenes(int n,int s)
{
int boolean[n-1];//boolean array holds 0 if the numbers is not prime
int list[n-1];//store the numbers till given range from 2 onwards
int ctr,outctr,inctr,primeassm;
for(ctr=0;ctr<n-1;ctr++)
{
list[ctr]=ctr+2;//start storing numbers from 2 onwars
boolean[ctr]=1;//assume all to be prime
}
for(outctr=0;outctr<n/2+1;outctr++)
{
if(boolean[outctr]==1)
{
primeassm=list[outctr];//perform primality check for indivusal numbers
for(inctr=outctr+1;inctr<n-1;inctr++)
if(list[inctr]%primeassm==0)//if divisible set boolean to 0
boolean[inctr]=0;
}
}
printf(" The prime numbers from %d to %d are ",s,n);
for(ctr=0;ctr<n-1;ctr++)
if(boolean[ctr]==1 && ctr>=s-2)//display the list of prime numbers
printf("%d " ,list[ctr]);
}
int main()
{
int beg,num;
printf("ENTER THE begining and end value in integers ");
scanf("%d%d",&beg,&num);
if(beg<num)
{
Eratosthenes(num,beg);
}
else printf("the given input is not valid ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.