Home »
C++ Programs
C++ program to find the product of prime numbers in a range using class
Submitted by Shubh Pachori, on September 01, 2022
Problem statement
Given a range, we have to find the product of prime numbers in that range using the class and object approach.
Example:
Input:
Enter Range: 1 9
Output:
Prime Numbers in the range 1 to 9 are 1 2 3 5 7
Product of prime numbers in range is 210
C++ code to find the product of prime numbers in a range using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Prime {
// declare private data members
private:
int start, end;
// public functions
public:
// getRange() function to insert range
void getRange() {
cout << "Enter Range: ";
cin >> start >> end;
}
// productPrime() function to print the product
// of prime numbers in between range
int productPrime() {
// initilaize int type variables
// to perform operations
int index_1, index_2, product = 1, check = 1;
cout << "Prime Numbers in the range " << start << " to " << end << " are ";
// for loop to search prime number in the range
for (index_1 = start; index_1 <= end; index_1++) {
// counter variable
int check = 0;
// for loop for checking if the number is prime or not
for (index_2 = 2; index_2 < index_1; index_2++) {
// if condition to check if the index_1
// is divisible by the index_2
if (index_1 % index_2 == 0) {
// counter increased by 1
check++;
// break statement to break the loop
break;
}
}
// if the counter is zero then the index_1 number
// is printed and multiplied to the product
if (check == 0) {
cout << index_1 << " ";
// multiplying prime numbers
product = product * index_1;
}
}
// returning product
return product;
}
};
int main() {
// create an object
Prime P;
// int type variable to store product
// of prime numbers
int product;
// calling getRange() function to
// insert range
P.getRange();
// productPrime() function to
// multiply prime numbers in the range
product = P.productPrime();
cout << "\nProduct of prime numbers in range is " << product;
return 0;
}
Output
RUN 1:
Enter Range: 2 11
Prime Numbers in the range 2 to 11 are 2 3 5 7 11
Product of prime numbers in range is 2310
RUN 2:
Enter Range: 10 20
Prime Numbers in the range 10 to 20 are 11 13 17 19
Product of prime numbers in range is 46189
Explanation
In the above code, we have created a class Prime, two int type data members start and end to store the start and end of the range, and public member functions getRange() and productPrime() to store range and to print product of the prime numbers in between that given range.
In the main() function, we are creating an object P of class Prime, reading a range by the user using getRange() function, and finally calling the productPrime() member function to print the product of prime numbers in the given range. The productPrime() function contains the logic to print the product of prime numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »