Program to check whether every rotation of a number is prime or not in Python

Suppose we have a number n, we have to check whether every rotation of n is prime or not.

So, if the input is like n = 13, then the output will be True, as 13 is prime, 31 is also prime.

To solve this, we will follow these steps −

  • n := n as string
  • do a loop for size of n times, do
    • if n is not a prime number, then
      • return False
    • n := n[from index 1 to end] concatenate first character of n
  • return True

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, n):
      def is_prime(n):
         if n<=1: return False
            return not any(n%2==0 or n%i==0 for i in range(3,int(n**0.5)+1,2))
      n = str(n)
      for _ in range(len(n)):
         if not is_prime(int(n)):
            return False
            n = n[1:] + n[0]
      return True
ob = Solution()