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 product of digits at even places of a number is divisible by K in Python
Sometimes we need to check if the product of digits at even positions (counting from right to left) of a number is divisible by another number. In this problem, the rightmost digit is at position 1, the next digit is at position 2, and so on.
For example, in the number 59361, the digits at even positions are 6 (position 2), 9 (position 4), making the product 6 × 9 = 54. If we need to check divisibility by 3, then 54 ÷ 3 = 18, so it's divisible.
Algorithm
To solve this problem, we follow these steps ?
- Calculate the total digit count of the given number n
- Initialize product as 1
- While n > 0, do:
- If current digit_count is even, multiply product by the last digit
- Remove the last digit from n by integer division
- Decrease digit_count by 1
- Return True if product is divisible by k, otherwise False
Example
Let's implement this solution using Python ?
from math import log10
def solve(n, k):
digit_count = int(log10(n)) + 1
prod = 1
while n > 0:
if digit_count % 2 == 0:
prod *= n % 10
n = n // 10
digit_count -= 1
if prod % k == 0:
return True
return False
# Test the function
n = 59361
k = 3
result = solve(n, k)
print(f"Number: {59361}")
print(f"Digits at even positions: 6 (pos 2), 9 (pos 4)")
print(f"Product: 6 × 9 = {6*9}")
print(f"Is {6*9} divisible by {k}? {result}")
Number: 59361 Digits at even positions: 6 (pos 2), 9 (pos 4) Product: 6 × 9 = 54 Is 54 divisible by 3? True
How It Works
For the number 59361:
- Position 1 (rightmost): 1 (odd position, skip)
- Position 2: 6 (even position, include in product)
- Position 3: 3 (odd position, skip)
- Position 4: 9 (even position, include in product)
- Position 5: 5 (odd position, skip)
Product = 6 × 9 = 54, and 54 % 3 = 0, so the result is True.
Alternative Approach
Here's another way to solve this by converting the number to a string ?
def solve_alternative(n, k):
digits = str(n)
length = len(digits)
prod = 1
for i in range(length):
# Position from right is (length - i)
position_from_right = length - i
if position_from_right % 2 == 0:
prod *= int(digits[i])
return prod % k == 0
# Test both approaches
n = 59361
k = 3
print("Method 1 (using log10):", solve(n, k))
print("Method 2 (using string):", solve_alternative(n, k))
Method 1 (using log10): True Method 2 (using string): True
Conclusion
Both approaches effectively find digits at even positions and check divisibility. The mathematical approach using log10() is more memory-efficient, while the string approach is more intuitive and easier to understand.
