There are integers with 77 digits such that the sum of any three consecutive digits within the integer is at most 7. Find and input the last three digits as your answer.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
This is a nice application of dynamic programming. Note that if we have a satisfying number x of n digits, we can extend it to n + 1 digits easily: just consider the last two digits a , b of x , and append a digit c where a + b + c ≤ 7 . All the previous digits are not affected by the addition of c ; if they satisfy the condition (sum of three consecutive digits is at most 7), they will also satisfy it now. Thus we can do dynamic programming. We will keep track of three states: number of digits, second-last digit, and last digit. We abbreviate this as
dp[n, a, b]
. This counts the number of satisfying integers that has n digits, whose last two digits are a , b (where a is the tens and b is the units digit).As the base cases, any two digit number a b with a = 0 satisfies the condition vacuously , just because there is no string of three consecutive digits. Thus
dp[2, a, b]
is equal to 1 for all a = 0 .For the actual dynamic programming work, we simply translate the above observation into code. Suppose we have three digits a , b , c where a + b + c ≤ 7 . Then every number of n − 1 digits that ends with a , b can be extended into a number of n digits that ends with b , c . In other words, we can add
dp[n-1, a, b]
todp[n, b, c]
. There's trivially no overlap, because different a , b , c give different numbers. Now we just iterate that over all a , b , c to fill our dynamic programming state of n digits, and then iterate that over n so we obtain the numbers for 77 digits.Finally, once it's done, we simply add up everything together: we sum
dp[77, a, b]
over all a , b to give the answer.Python 3 code follows. This explains why I select to choose commas instead of a more common multi-dimensional array
dp[n][a][b]
, because it's easier to initialize adict
type whose keys are tuples(n, a, b)
, instead of a layeredlist
type with a layer forn
, a layer fora
, and a layer forb
.(The actual number before modulo is 13080748169314291086539372946324303289341309985718.)
Now that you've done this, try Project Euler 164 .