Check if any permutation of a number is divisible by 3 and is Palindromic in Python

PythonServer Side ProgrammingProgramming

Suppose, we are provided with a large positive integer number N. We have to check if we can find out a number from its digit-permutations; such that the permutation is equal to its reverse form, i.e. its palindrome, and is also divisible by 3.

For example, suppose we have the number 132213. If we check the permutations from the digits of the number, we get 123321 which is a palindrome and is also divisible by 3. We have to check whether any of the permutations possible from the input number satisfy the above conditions.

So, if the input is like: input_num = 132213, then the output will be "One or more permutation is a palindrome and is divisible by three".

To solve this, we will follow these steps −

  • digit_array := a new list of size 10 initialized with 0s
  • input_sum := 0
  • while input_num is not zero, do
    • input_sum := input_sum + (input_num mod 10)
    • digit_array[input_num mod 10] := digit_array[input_num mod 10] + 1
    • input_num := floor value of (input_num / 10)
  • if input_sum mod 3 is not same as 0, then
    • return False
  • index_odd := 0
  • for i in range 0 to 9, do
    • if digit_array[i] mod 2 is not same as 0, then
      • index_odd := index_odd + 1
  • if index_odd > 1, then
    • return "No permutation is a palindrome and is divisible by three"
  • otherwise,
    • return "One or more permutation is a palindrome and is divisible by three"

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(input_num):
   digit_array = [0] * 10
   input_sum = 0
   while (input_num) :
      input_sum += input_num % 10 digit_array[input_num % 10] += 1
      input_num //= 10
   if (input_sum % 3 != 0):
      return False
   index_odd = 0
   for i in range(10) :
      if (digit_array[i] % 2 != 0):
         index_odd += 1
   if (index_odd > 1):
      return "No permutation is a palindrome and is divisible by three"
   else:
      return "One or more permutation is a palindrome and is divisible by three"
input_num = 132213
print(solve(input_num))

Input

132213

Output

One or more permutation is a palindrome and is divisible by three
raja
Published on 30-Dec-2020 13:07:10
Advertisements