Sub topic 3
Digit sums and remainders modulo 9 and 3
This chapter assumes you can do long division with remainders, know the powers of 10, and can write simple linear equations. It also assumes you understand place value in base 10, which the earlier chapters covered.
Digit sums and remainders
A number leaves the same remainder when divided by 9 as its digit sum does. Each power of 10 leaves remainder 1 when divided by 9, so each digit contributes just its own value. The same holds for 3.
def digit_sum(n):
return sum(int(d) for d in str(n))
print(digit_sum(7384)) # 22
print(7384 % 9) # 4
print(digit_sum(7384) % 9) # 4Apply this to a question directly. The remainder when 5273418 is divided by 9 equals the digit sum 30 reduced mod 9, which is 3.
Divisibility rules for 3, 9, 11 and friends
A number is divisible by 9 when its digit sum is divisible by 9, and by 3 when its digit sum is divisible by 3.
Divisibility by 11 uses an alternating sum. Starting from the units digit, add and subtract digits in turn. If the result is divisible by 11, so is the number.
def alt_sum(n):
s = str(n)
return sum((-1) ** k * int(d) for k, d in enumerate(reversed(s)))
print(alt_sum(2728)) # 11, so 2728 is divisible by 11For 4 and 8, check the last two or three digits. Divisibility by 6 needs both 2 and 3.
Counting digits in 1 to n
Count numbers by their number of digits. The numbers 1 to 9 use one digit each, 10 to 99 use two each, and 100 to 999 use three each.
def digits_used(n):
return sum(len(str(i)) for i in range(1, n + 1))
print(digits_used(99)) # 189
print(digits_used(999)) # 2889Counting a digit's occurrences
Count each position separately. The digit 1 appears in the units place for 1, 11, ..., 91 (10 times), in the tens place for 10 to 19 (10 times), and once in 100. The total is 21.
def count_digit(d, n):
return sum(str(i).count(str(d)) for i in range(1, n + 1))
print(count_digit(1, 100)) # 21Checking answers and choosing the fastest method
Casting out nines checks multiplication. For 45 × 23 = 1035, the digit sums are 0 and 5 for the factors, giving 0 × 5 = 0 mod 9. The digit sum of 1035 is 9, which is 0 mod 9, so the product passes the check.
Exercise
What is the remainder when 5273418 is divided by 9?
Show answer
The digit sum is 30, and 30 mod 9 = 3, so the remainder is 3. Q: How many digits are used to write the numbers 1 to 150? A: Numbers 1 to 9 use 9 digits, 10 to 99 use 180, and 100 to 150 use 3 × 51 = 153. The total is 342.