Check whether the sum of absolute difference of adjacent digits is Prime or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether the sum of the absolute difference of adjacent digit pairs is prime or not.

So, if the input is like n = 574, then the output will be True as |5-7| + |7-4| = 5, this is prime.

To solve this, we will follow these steps −

  • num_str := n as string
  • total := 0
  • for i in range 1 to size of num_str - 1, do
    • total := total + |digit at place num_str[i - 1] - digit at place num_str[i]|
  • if total is prime, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def isPrime(num):
   if num > 1:
      for i in range(2, num):
         if num % i == 0:
           return False
      return True
   return False
     
def solve(n):
   num_str = str(n)
   total = 0
   for i in range(1, len(num_str)):
      total += abs(int(num_str[i - 1]) - int(num_str[i]))
        
   if isPrime(total):
      return True
   return False
      
n = 574
print(solve(n))

Input

574

Output

True
raja
Published on 16-Jan-2021 05:01:44
Advertisements