- 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 sum of digits at odd places of a number is divisible by K in Python
Suppose we have a number n and another number k, we have to check whether the sum of digits of n at it's odd places (from right side to left side) is divisible by k or not.
So, if the input is like n = 2416 k = 5, then the output will be True as sum of odd placed numbers from right to left is 4 + 6 = 10. Which is divisible by 5.
To solve this, we will follow these steps −
- total := 0, pos := 1
- while n > 0 , do
- if pos is odd, then
- total := total + (n mod 10)
- n := quotient of (n / 10)
- pos := pos + 1
- if pos is odd, then
- if total is divisible by k, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(n, k): total = 0 pos = 1 while n > 0: if pos % 2 == 1: total += n % 10 n = n // 10 pos += 1 if total % k == 0: return True return False n = 2416 k = 5 print(solve(n, k))
Input
2416, 5
Output
True
Advertisements