A number is said to be a circular prime if all its possible rotations are also prime numbers.
In the code below, we have used the
is_prime() method to check whether or not a number is prime. In order to get our new rotation, we simply get the last digit of the number and place it at the start.
# Function to check a number is a circular # prime or not # number is passed as a string, so number of # digits is evaluated easily. def is_circular_prime(number): i = remainder = value = total = 0 digits = len(number) num = int(number) # Here we will pick the last digit and # place it at the start in order to form # a new rotation. # 199 -> 919 -> 991 while i < digits: # Dividing the number in digits # 199 % 10 = 9(last digit) remainder = int(num % 10) num = int(num / 10) num = int((remainder * (10 ** (digits - 1)) + num)) print(num) value = is_prime(num) total += value i += 1 if total is digits: print("Circular Prime") else: print("Non-Circular Prime") # Function to check number is a prime or not def is_prime(num): count = 0 for i in range(1,num+1): if num % i is 0: count += 1 if count is 2: return 1 else: return 0 # Driver Function is_circular_prime("199")
View all Courses