È stato utile?

Domanda

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

PythonServer Side ProgrammingProgramming

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 −

Example

 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()
print(ob.solve(13))

Input

13

Output

True
raja
Published on 05-Oct-2020 09:52:41
Advertisements
È stato utile?
Non affiliato a Tutorialspoint
scroll top