This year, New Scientist has embarked on a new series for their puzzle column called the “Brain Twister.” I believe it will be a fun exercise for me to tackle these puzzles using Python, as I aim to improve my coding skills. The problem that we’re gonna solve in this post is “Digital Sevens”.
Problem:
61, 14234, 25, 1111111 and 95 are all numbers whose digits add to a multiple of 7.
Questions:
(1) What is the next number after 95 whose digits add to a multiple of 7?
(2) Can you find a pair of consecutive numbers whose digits both add to multiples of 7?
(3) What about a pair of numbers under 100 whose digits both add to multiples of 7, but that are two apart rather than consecutive?
Solution:
Firstly, since this problem is about digital sums, we need to write a function that computes the sum of digits of a number.
def sum_digits(n):
sum = 0
while n:
sum += n % 10
n //= 10
return sum
(1) What is the next number after 95 whose digits add to a multiple of 7?
num = 96
while sum_digits(num) % 7 != 0:
num += 1
print('Next number after 95 whose digits add to a multiple of 7 is:', num)
# Answer:
# Next number after 95 whose digits add to a multiple of 7 is: 106
Answer: The next number after 95 whose digits add to a multiple of 7 is 106.
(2) Can you find a pair of consecutive numbers whose digits both add to multiples of 7?
num = 0
while sum_digits(num) % 7 != 0 or sum_digits(num+1) % 7 != 0:
num += 1
print(f'The smallest pair of consecutive numbers whose digits
both add to multiples of 7 is: ({num},{num+1})')
# Answer:
# The smallest pair of consecutive numbers whose digits
# both add to multiples of 7 is: (69999,70000)
Answer: The smallest pair of consecutive numbers whose digits both add to multiples of 7 is (69999,70000).
(3) What about a pair of numbers under 100 whose digits both add to multiples of 7, but that are two apart rather than consecutive?
num = 0
print('Pairs of numbers under 100 whose digits both add to multiples of 7,
but are two apart:')
while num < 99:
if sum_digits(num) % 7 == 0 and sum_digits(num+2) % 7 == 0:
print((num, num+2))
num += 1
# Answer:
# Pairs of numbers under 100 whose digits both add to multiples of 7,
# but are two apart:
# (59, 61)
# (68, 70)
Answer: Pairs of numbers under 100 whose digits both add to multiples of 7, but are two apart: (59, 61) and (68, 70).
And that’s all for this digital sevens 7️⃣ problem. Any feedback or questions are welcome! The code is available on my Github. Check out the other problems in this series:
Thank you for reading! :)
Reference: