Circular Prime

Circular Prime


A Circular Prime is a prime number that remains prime under cyclic shifts of its digits. When the leftmost digit is removed and replaced at the end of the remaining string of digits, the generated number is still prime. The process is repeated until the original number is reached again.

A number is said to be prime if it has only two factors 1 and itself.

Example:

131
311
113
Hence, 131 is a circular prime.

Test your program with the sample data and some random data:

Example 1

INPUT:
N = 197

OUTPUT:
197
971
719
197 IS A CIRCULAR PRIME

Example 2

INPUT:
N = 1193

OUTPUT:
1193
1931
9311
3119
1193 IS A CIRCULAR PRIME

Example 3

INPUT:
N = 29

OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME
import java.io.*;

class ISCprac2016Q01
{
    public static void main(String arg[])throws IOException
    {
        int l,i,n;
        boolean flag = true;

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a number : ");
        String num = br.readLine();

        l = num.length();

        for(i = 0; i < l; i++){

            String str = num.substring(i,l) + num.substring(0,i);

            n = Integer.parseInt(str);

            if(!isPrime(n)){
                flag = false;
                break;
            }

        }

        if(flag)
            System.out.println(num + " IS A CIRCULAR PRIME");   
        else
           System.out.println(num + " IS NOT A CIRCULAR PRIME");  
    }//end of main

   //Return true if number is prime else return false
    private static boolean isPrime(int p){

        for(int i = 2; i <= p/2; i++){
            if(p%i == 0)
                return false;
        }
        return true;

    }//end of isPrime

}//end of class

Have something to say? Log in to comment on this post.

0 comments