The Program in C++ Program to check if a given number is circular prime or not is given below:
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
vector<int> rotate(int num) {
vector<int> rotations;
string numStr = to_string(num);
for (int i = 0; i < numStr.length(); i++) {
rotate(numStr.begin(), numStr.begin() + 1, numStr.end());
rotations.push_back(stoi(numStr));
}
return rotations;
}
bool isCircularPrime(int n) {
vector<int> rotations = rotate(n);
for (int i : rotations) {
if (!isPrime(i)) {
return false;
}
}
return true;
}
int main() {
int n;
cout << "Hello Codeauri Family,Enter a number here to check whether it is a circular prime number or not!:\n ";
cin >> n;
if (isCircularPrime(n)) {
cout << n << " is a Circular Prime." << endl;
} else {
cout << n << " is not a Circular Prime." << endl;
}
return 0;
}
Output:
Hello Codeauri Family,Enter a number here to check whether it is a circular prime number or not!:
1193
1193 is a Circular Prime.
Pro-Tips💡
This program implements a function isPrime
to check if a number is prime.
The function returns false if the number is less than or equal to 1 or is divisible by any number between 2 and the square root of n
.
The function rotate
uses the to_string
function to convert num
to a string, then uses the rotate
algorithm to rotate the first character of the string to the end, repeating the process numStr.length()
times.
The rotate
function returns a vector of the rotated numbers. The isCircularPrime
function uses the rotate
function to find all rotations of n
and uses the isPrime
function to check if each rotation is prime.
If all rotations are prime, the function returns true, indicating that n
is a Circular Prime.
The main
function prompts the user to enter a number and calls the isCircularPrime
function with the input.
If the function returns true, the number is a Circular Prime and the program prints a message to that effect.
If the function returns false, the number is not a Circular Prime and the program prints a message to that effect.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.