# digit.py # Let's empirically determine the answers to 3 questions. # If you write out the integers from 1 to 1,000,000, # 1. How many numbers contain exactly one 5 # 2. How many numbers contain at least one 5 # 3. How many 5s would be written # It doesn't matter if it's "5", but if I said 1 or 0 we'd be a bit sensitive # about starting at 1 and ending at 1,000,000 instead of 0 to 999,999. # Since we don't care about appearances of 0, we may assume leading zeros. # Hopefully, these empirical results should inspire # the correct procedure for counting these occurrences. # For 1 to 1 million, the program takes about 1 second to run. exactCount = 0 atLeastCount = 0 totalCount = 0 max = 1000000 n = 1 while n <= max: s = str(n) howOften = s.count('5') if howOften == 1: exactCount += 1 if howOften >= 1: atLeastCount += 1 totalCount += howOften n += 1 print("Numbers from 1 to " + str(max)) print("Containing exactly one 5: " + str(exactCount)) print("Containing at least one 5: " + str(atLeastCount)) print("Total 5's written: " + str(totalCount)) ''' various results: Numbers from 1 to 1000000 Containing exactly one 5: 354294 = 6 * 9^5 Containing at least one 5: 468559 = 10^6 - 9^6 Total 5's written: 600000 = 6 * 10^5 To think about "at least 5", can count indirectly: Consider if we didn't want any 5's at all, and subtract from total. Hence, 10^6 - 9^6. With more toil, 468559 can also be obtained via inclusion/exclusion: C(6,1) * 100,000 = 600,000 - C(6,2) * 10,000 - 150,000 + C(6,3) * 1,000 + 20,000 - C(6,4) * 100 - 1,500 + C(6,5) * 10 + 60 - C(6,6) * 1 - 1 Numbers from 1 to 1000 Containing exactly one 5: 243 = 3 * 9^2 Containing at least one 5: 271 = 10^3 - 9^3 Total 5's written: 300 = 3 * 10^2 How do we count 243 containing exactly one 5? If 5 is the first digit, we only have 9*9 choices for other two digits: 81 And we multiply by the number of digit places the 5 could be in. In general, our answer is (# digits) * 9 ^ (# digits - 1) Therefore, for 6 digits, we have 6 * 9^5 = 254294. '''