circular prime number program in java

Java Program for Circular Prime


Java Program for Circular Prime

According to Wikipedia, A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will be prime.

Examples : 113, 197, 199, 337, 1193, 3779, 11939, 19937 etc


Say 113 -> 131 -> 311 is circular prime.


import java.util.*;
public class CircularPrime
{
    int n, m, c, f, i, a, b, j, f1; // Instance Variables
    void circularPrime(int x)  
    {
        c=0; // Total Digit Calculate
        n=x;
        f=0;
        while(n!=0)
        {
            n/=10;
            c++;
        }
        n=x;
        System.out.println("Output");
        System.out.println("======");
        for(i=0;i<c;i++)
        {

            f=isPrime(n); // Returing 1 if Prime or 0 if not prime
            if(f==1)
                System.out.println(n);
            else
            {
                System.out.println("Not a Circular Number");
                break;
            }
            // Example 113 113 -> 131 -> 311
            a=n%((int)Math.pow(10,c-1));    // Reminder 13
            b=n/((int)Math.pow(10,c-1));      // quotient 1  
            m=a*10+b;                                 // here m = 13 * 10 + 1 =131
            n=m;                                           // then n = 131 this process repeated till the loop end
        }
        if(f==1)
        System.out.println("Circular Prime");
    }
    // Prime checking method which return 1 if prime else 0
    int isPrime(int x)
    {
        f1=1;
        for(j=2;j<x;j++)
        {
            if(x%j==0)
            {
                f1=0;
                break;
            }
        }
        return f1;
    }
    // Main method
    public static void main(String args[])
    {
        int n,m,c,f,i;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number :");
        n= sc.nextInt();
        CircularPrime ob=new CircularPrime();
        ob.circularPrime(n);
    }

}

Sample output
Enter a number :
113
Output
======
113
131
311
Circular Prime
Enter a number :
137
Output
======
137
Not a Circular Number

In the above program, I have used two used to define methods, namely circularPrime() and isPrime(). The circularPrime(int x) takes a value and first it find out the number of digits in the given number. After then isPrime(n) is checking number is prime or not and it checks again after interchanging the number in this fashion 113 -> 131 -> 311

More Java program





SHARE THIS
Previous Post
Next Post