Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to check whether every rotation of a number is prime or not in Python
In this problem, we need to check if all possible rotations of a given number are prime numbers. A rotation means moving digits from the front to the back or vice versa.
So, if the input is like n = 13, then the output will be True, as 13 is prime and its rotation 31 is also prime.
Algorithm
To solve this, we will follow these steps ?
- Convert the number to string format
- For each possible rotation of the number:
- Check if the current rotation is prime
- If any rotation is not prime, return False
- Generate next rotation by moving first digit to the end
- If all rotations are prime, return True
Example
Let's implement this solution with a helper function to check if a number is prime ?
class Solution:
def solve(self, n):
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
n = str(n)
for _ in range(len(n)):
if not is_prime(int(n)):
return False
n = n[1:] + n[0] # Rotate: move first digit to end
return True
# Test the solution
ob = Solution()
print(ob.solve(13))
print(ob.solve(17)) # 17 and 71 are both prime
print(ob.solve(19)) # 19 and 91 (91 = 7×13, not prime)
The output of the above code is ?
True True False
How It Works
The algorithm works as follows:
-
Prime Check: The
is_prime()function efficiently checks if a number is prime by testing divisibility up to its square root -
String Rotation: We convert the number to string and use slicing
n[1:] + n[0]to rotate digits - Complete Check: We test all possible rotations (equal to the number of digits) and return False if any rotation is not prime
Key Points
- Numbers with even digits (except 2) in rotations will likely fail since they become even
- The time complexity is O(k × ?m) where k is the number of digits and m is the maximum value of rotations
- This approach handles edge cases like single-digit numbers and numbers containing 0
Conclusion
This solution efficiently checks all rotations of a number for primality using string manipulation and an optimized prime checking function. The key insight is converting to string format for easy digit rotation.
Advertisements
