1. Create a class: “Prime” with private data members: upper_limit (int), lower_limit (int) and parameterized constructor, which initializes the values of both data members. Apart from initialization, this constructor also displays the count of prime numbers from upper_limit to lower_limit. [Example: upper_limit:15, lower_limit:10, count of prime numbers is:2 (11 and 13), also make sure the value of upper_limit should be greater than lower_limit].
#include <iostream>
#include <stdexcept>
#include <vector>
class Prime
{
int lower_limit;
int upper_limit;
static bool IsPrime(int n)
{
if(n < 2) return false;
if(n == 2) return true;
if(n % 2 == 0) return false;
for(int i = 3; i * i <= n; i += 2)
{
if(n % i == 0) return false;
}
return true;
}
public:
Prime(int lowerLimit, int upperLimit)
:lower_limit(lowerLimit), upper_limit(upperLimit)
{
if(upper_limit < lower_limit)
{
throw std::invalid_argument("the value of upper_limit should be greater than lower_limit");
}
if(lower_limit < 0 || upper_limit < 0)
{
throw std::invalid_argument("the value of upper_limit and lower_limit should be positive");
}
std::vector<int> primes;
for(int i = lower_limit; i <= upper_limit; ++i)
{
if(IsPrime(i))
{
primes.push_back(i);
}
}
std::cout << "upper_limit:" << upper_limit
<< ", lower_limit:" << lower_limit
<< ", count of prime numbers is:" << primes.size();
if(primes.empty())
{
std::cout << "\n";
}
else
{
for(size_t i = 0; i < primes.size(); ++i)
{
if(i == 0)
{
std::cout << " (" << primes[i];
}
else
if(i != primes.size() - 1)
{
std::cout << ", " << primes[i];
}
else
{
std::cout << " and " << primes[i] << ")\n";
}
}
}
}
};
int main()
{
std::cout << "Please input two positive integers: ";
int n1, n2;
std::cin >> n1 >> n2;
if(!std::cin)
{
std::cerr << "Bad input\n";
return 1;
}
try
{
Prime prime(n1, n2);
return 0;
}
catch(std::exception& e)
{
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
Comments
Leave a comment