- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check whether the sum of absolute difference of adjacent digits is Prime or not in Python
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
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
Advertisements