Circular Prime in Python

Hello everyone, if you are looking for a program to determine or check if a number is a circular prime or not in Python then you are in the right place.

How to check if a number is a circular prime or not in Python

First, let us take a look at what a circular prime number is:

A number can be referred to as circular prime only if the number generated at each intermediate step when cyclically permuting its (base 10) digits will be prime. For example :

  1. 113
  2. 311
  3. 131

All the numbers are prime so it is a circular prime number.

Python program: Finding Circular Prime

def isprime(num):
    count=0
    for i in range(1,num+1):
        if(num % i ==0):
            count+=1
    if(count==2):
        return 1
    else:
        return 0


digit=0
i=0
rem=0
sum=0
check=input("enter the number: ")
length=len(check)
num=int(check)
while(i<length):
    rem=int(num % 10)
    num=int(num / 10)
    num=int((rem * (10 ** (length - 1)) + num))
    print(num)
    digit=isprime(num)
    sum=sum+digit
    i+=1
if(sum==length):
    print("Circular Prime")
else:
    print("Non-Circular Prime")

Output :

enter the number: 197
719
971
197
Circular Prime
Explanation :
  1. Before the beginning of the program, we create a method to determine if a number is prime or not. It works by taking in input and finding its factors if the number of factor is greater than 2. We return 1, else we return 0.
  2. Coming to the main body, we declare variables such as ‘i’, ‘rem’, ‘digit’, ‘sum’ and initialize it to 0.
  3. We then take a variable for input in type String, we get its length and then convert it into type integer.
  4. Thereafter use a while loop to control the execution of the program.
  5. We extract the last digit of the number and multiply it with 10 raised to the power of length of the program, and add the rest of the digits in its back and then check if the number is prime.
  6. If true we iterate counter with one. Once the loop terminates we check if the counter equals to the actual length of the number if True, then we print it out as a Circular Prime number.

Leave a Reply

Your email address will not be published. Required fields are marked *