Write a C++ program using the concept of OOP to check whether a number is prime or not.
Algorithm:
- Create a PrimeChecker class with private variable number to store the number which is to be checked for prime or not.
- Define a public method isPrime() in the class to check whether the number is prime or not by using some mathematical logic and return boolean value as true if the number is prime and false if it is not.
- In the main() function, prompt the user to enter a number.
- Create a PrimeChecker object with the number entered by the user.
- Call the isPrime() method of the PrimeChecker object to check whether the entered number is prime or not.
- Print the result of the prime check (prime or not prime).
- End the program.
Coding in C++:
#include <iostream>
using namespace std;
class PrimeChecker {
private:
int number;
public:
PrimeChecker(int num) {
number = num;
}
bool isPrime() {
if (number <= 1) return false;
if (number <= 3) return true;
if (number % 2 == 0 || number % 3 == 0) return false;
for (int i = 5; i * i <= number; i = i + 6) {
if (number % i == 0 || number % (i + 2) == 0)
return false;
}
return true;
}
};
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
PrimeChecker pc(num);
if (pc.isPrime()) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
return 0;
}
Prime number using sieve of eratosthenes method:
#include<iostream>
using namespace std;
class Prime{
public:
bool sieveMethod(int n){
if (n <= 1) return false;
bool sieve[n + 1];
for(int i = 0; i <= n; i++){
sieve[i] = true;
}
sieve[0] = false; sieve[1] = false;
for(int i = 2; i * i<= n; i++){
if(sieve[i] == true){
for(int j = i * i; j <= n; j = j + i){
sieve[j] = false;
}
}
}
return sieve[n];
}
};
int main()
{
Prime obj;
cout<<obj.sieveMethod(11)<<endl;
return 0;
}
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment