Program opened below. You can scroll through the algorithm, Java code and output.
Program 50
Circular Prime Number
Question
Accept a positive integer and determine whether it is a circular prime.
Algorithm
Step 1: Start the program and accept a positive integer.
Step 2: Count the number of digits in the integer.
Step 3: Calculate the highest place value needed to rotate the last digit to the front.
Step 4: Define a method that tests whether an integer is prime.
Step 5: Reject values smaller than two as non-prime.
Step 6: Test possible divisors from two while the divisor's square does not exceed the number.
Step 7: If a divisor divides the number exactly, report that it is not prime.
Step 8: Test the original number for primality.
Step 9: Move the last digit to the front to form the next circular rotation.
Step 10: Test every rotation for primality.
Step 11: Continue until the original number of rotations has been tested.
Step 12: If all rotations are prime, report Circular Prime; otherwise report Not Circular Prime.
Step 13: Stop the program.
Java program
Javaimport java.util.*;
class CircularPrime
{
static boolean prime(int n)
{
if (n < 2)
{
return false;
}
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt(), t = n, digits = 0, place = 1;
while (t > 0) { digits++;
t /= 10;
}
for (int i = 1; i < digits; i++)
{
place *= 10;
}
int rot = n;
boolean circular = true;
for (int i = 0; i < digits; i++)
{
if (!prime(rot))
{
circular = false;
}
rot = (rot % 10) * place + rot / 10;
}
if (circular)
{
System.out.println("Circular prime");
}
else
{
System.out.println("Not a circular prime");
}
}
}Sample output
Input: Input: 197
Output: Circular prime (rotations: 197, 719, 971)