Circular Prime in Python using Recursion

Write an iterative/recursive function which takes one number as function argument and checks whether the number is circular prime number or not.

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

For example, 1193 is a circular prime, since1931, 9311, and 3119 are also prime.

The first few circular primes are 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97, 113, 131, 197, …

def circularPrime(num, step = 1):
    f = 0
    count = len(str(num))
    for i in range(1, num + 1):
        if num % i == 0:
            f = f + 1
    if f != 2:
        return False
    if count == step:
        return True
    s = str(num)
    n = int(s[1:] + s[0])
    return circularPrime(n, step + 1)

num = int(input("Enter the number: "))
if circularPrime(num):
    print(str(num) + " is a Circular Prime.")
else:
    print(str(num) + " is NOT a Circular Prime.")

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.