Create programs that, given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.
1
Expert's answer
2013-02-04T10:51:09-0500
#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;
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; }
Comments
Leave a comment