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

Given a number a N and the task is to check weather the sum of absolute difference of adjacent digit is a prime or not.

Examples:

Input: N = 142 
Output: Prime
Sum = |1-4| + |4-2| = 5 i.e. prime.

Input: N = 347
Output: Not prime

Approach: Find the sum of absolute difference of adjacent digits and then check if that sum is prime or not.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the above approach
import math as mt
  
# Function to check for a prime number
def Prime(n):
      
    if n == 1:
        return False
          
    for i in range(2, mt.ceil(mt.sqrt(n + 1))):
        if n % i == 0:
            return False
    return True
      
# Function to find the sum of array
def checkSumPrime(string):
    summ = 0
    for i in range(1, len(string)):
        summ+= abs(int(string[i-1])-int(string[i]))
          
    if Prime(summ):
        return True
    else:
        return False
  
# Driver code
num = 142
  
string = str(num)
  
s =[i for i in string]
  
if checkSumPrime(s):
    print("Prime")
else:
    print("Not Prime\n")

chevron_right


Output:

Prime


My Personal Notes arrow_drop_up