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 :
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")
enter the number: 197 719 971 197 Circular Prime
- 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.
- Coming to the main body, we declare variables such as ‘i’, ‘rem’, ‘digit’, ‘sum’ and initialize it to 0.
- We then take a variable for input in type String, we get its length and then convert it into type integer.
- Thereafter use a while loop to control the execution of the program.
- 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.
- 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.