63 063
Assignments Done
99,1%
Successfully Done
In July 2018

Answer to Question #23636 in Java | JSP | JSF for Karl

Question #23636
Create programs that, given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.
Expert's answer
#include <iostream>
#include <math.h>
using namespace std;

/**
* This functionchecks if the number p is prime.
* It suffices toverify that p is not divisible by numbers from 2 to sqrt(p) */ int is_prime_number(int p) {
// skip numbers0 and 1 that are not primes
if (p<2)
{
returnfalse;
}
// number 2 isprime
if (p==2)return true;

float p_sqr =sqrt(p);
for(int i=2; i<= p_sqr; i++)
{
if ( p % i== 0 )
{
returnfalse;
}
}
return true;
}



int main()
{
int minX, maxX;
// get lowerand upper bounds from the user
cout <<"Enter lower bound for the range: ";
cin >>minX;

cout <<"Enter upper bound for the range: ";
cin >>maxX;

if (minX >maxX)
{
cout<< "Incorrect range. Quitting
";
return 0;
}
if (maxX<2)
{
cout<< "The range [" << minX << "," <<
maxX << "] contains no primes.
";
return 0;

}
// increaseminX to 2 if necessary, since there are no primes < 2
if (minX<2)minX=2;

cout <<"List of primes contained in the range [" << minX <<
"," << maxX << "]:
";
int cnt=0; //counter of primes
for(int i=minX;i<=maxX; i++)
{
if(is_prime_number(i))
{
cout<< i << " ";
cnt++;
}
}
if (cnt==0)
{
cout<< "No primes in this range";
}
cout <<endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions