Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether sum of digits at odd places of a number is divisible by K in Python
In this problem, we need to check whether the sum of digits at odd positions (counting from right to left) of a number is divisible by a given value k. The positions are counted starting from 1.
So, if the input is like n = 2416 and k = 5, then the output will be True. The digits at odd positions from right to left are: position 1 (digit 6) and position 3 (digit 4). Their sum is 4 + 6 = 10, which is divisible by 5.
Algorithm
To solve this problem, we will follow these steps ?
- Initialize total = 0 and pos = 1
- While n > 0, do:
- If pos is odd, then add the last digit (n mod 10) to total
- Remove the last digit: n = n // 10
- Increment pos by 1
- If total is divisible by k, return True, otherwise return False
Example
Let us see the following implementation to get better understanding ?
def solve(n, k):
total = 0
pos = 1
while n > 0:
if pos % 2 == 1: # Check if position is odd
total += n % 10 # Add the last digit
n = n // 10 # Remove the last digit
pos += 1 # Move to next position
if total % k == 0:
return True
return False
n = 2416
k = 5
print(solve(n, k))
True
Step-by-Step Execution
Let's trace through the example with n = 2416 and k = 5:
def solve_with_trace(n, k):
total = 0
pos = 1
original_n = n
print(f"Number: {original_n}, K: {k}")
print("Position | Digit | Add to sum?")
print("---------|-------|------------")
while n > 0:
digit = n % 10
if pos % 2 == 1: # Odd position
total += digit
print(f" {pos} | {digit} | Yes")
else:
print(f" {pos} | {digit} | No")
n = n // 10
pos += 1
print(f"\nSum of digits at odd positions: {total}")
print(f"Is {total} divisible by {k}? {total % k == 0}")
return total % k == 0
solve_with_trace(2416, 5)
Number: 2416, K: 5
Position | Digit | Add to sum?
---------|-------|------------
1 | 6 | Yes
2 | 1 | No
3 | 4 | Yes
4 | 2 | No
Sum of digits at odd positions: 10
Is 10 divisible by 5? True
Alternative Approach Using String
We can also solve this problem by converting the number to a string and accessing digits by index ?
def solve_string_approach(n, k):
num_str = str(n)
total = 0
# Iterate from right to left (reverse the string)
for i, digit in enumerate(reversed(num_str)):
if (i + 1) % 2 == 1: # Odd position (1-indexed)
total += int(digit)
return total % k == 0
# Test with the same example
n = 2416
k = 5
result = solve_string_approach(n, k)
print(f"Result using string approach: {result}")
Result using string approach: True
Conclusion
Both approaches effectively solve the problem by summing digits at odd positions from right to left. The mathematical approach processes digits by repeatedly dividing by 10, while the string approach reverses the number and uses indexing for position checking.
