Java program to check if a given number is Circular Prime or Not

Write a Java Program to check whether a number is circular Prime or Not. Let’s first understand what is Circular Prime number then will write Java code to check Circular Prime.

Circular Prime:  A prime number is said to be a circular prime if, after any cyclic permutations of the digits, it remains a prime.
Ex:  113 (All the possible permutations are: 311, 131 both are prime numbers)

Algorithm to find if the given no. is circular prime or not

We have to generate all the possible permutations of the given number and check if they are prime. If all prime numbers, then the given no. is a circular prime else not.

  • First, we will count the no. of digits in the given no.
  • Secondly, we will create a while loop that generates the next possible permutation of the given number. The while loop will be such that
  • It runs till the number is prime else will exit. It moves the last digit of the number to the first position.
    If the permutation inside while loop is equaled to the given number itself, the given no. is circular prime else not.

Java Program to find if the given no. is circular prime or not

import java.util.Scanner;
class CircularPrime
{
    public static void main (String[] args) 
    {
  Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
  if (isCircularPrime(n)) System.out.println("Circular Prime");
        else System.out.println("Not a Circular Prime");
    }

    private static booleanisPrime(int n)
    {
for(int i=2;i<=n/2;i++) if(n%i==0) return false;
        return true;
    }

    private static booleanisCircularPrime(int N)
    {
        int count = 0, temp = N;
        while (temp>0) 
        {
            count++;
            temp /= 10;
        }
        int num = N;
        while (isPrime(num)) 
        {
            int rem = num % 10;
            int div = num / 10;
            num = (int)((Math.pow(10, count - 1)) * rem)+ div;
            if (num == N) return true;
        }
            return false;
    }	
}

Input:  2

Output: Circular Prime

Input: 3

Output: Circular Prime

Input: 73

Output: Circular Prime

Input: 97

Output: Circular Prime

Input: 19

Output: Not a Circular Prime

Input: 23

Output: Not a Circular Prime

Input: 43

Output:  Not a Circular Prime