Problem 1020: Modified Sum of Fibonacci Numbers

View on Project Euler

Project Euler Problem 1020 Solution

Written in binary, every digit 1 of k in position i adds 2^i + 1 to the index k + s(k). Fibonacci numbers are entries of the powers of the matrix Q = [[1, 1], [1, 0]], so the sum over all k below 2^b becomes the product of the b factors I + Q^(2^i + 1), and the numbers from 0 to N split into one such block for each binary digit 1 of N + 1. With entries reduced modulo 10^9 + 7, N = 10^18 takes 229 multiplications of 2 x 2 matrices; a second method, based on Binet's formula with numbers a + b√5 modulo the prime, reads the binary digits in the opposite order and checks the result. Implementations are available in C++, Python and Java.

Detailed mathematical approach

Problem Summary

The Fibonacci numbers are defined by \(F_0=0\), \(F_1=1\) and \(F_k=F_{k-1}+F_{k-2}\) for \(k\ge2\), so that they begin \(0,1,1,2,3,5,8,13,\dots\), and \(s(k)\) denotes the number of ones in the binary representation of \(k\). For a non-negative integer \(N\) the problem defines

$$S(N)=\sum_{k=0}^{N}F_{k+s(k)},$$

gives \(S(10)=369\) and \(S(50)=161\,052\,232\,733\), and asks for \(S(10^{18})\) modulo \(10^9+7\). [1] The number \(s(k)\) is also known as the binary weight, the Hamming weight or the population count of \(k\). [2][3]

The sum has \(10^{18}+1\) terms, and the terms are enormous: \(F_n\) has about \(0.209\,n\) decimal digits, [4] so the last terms have about \(2\cdot10^{17}\) digits, and neither they nor the sum can be written out. The remainder of the sum modulo \(p=10^9+7\), however, can be found with a few hundred multiplications of small matrices, thanks to two observations. The first concerns the index: a binary digit \(1\) in position \(i\), counting the positions from \(0\) at the right, contributes \(2^i\) to \(k\) and \(1\) to \(s(k)\), so \(k+s(k)\) is the sum of the numbers \(2^i+1\) over the positions \(i\) of the digits \(1\) of \(k\). The second concerns the Fibonacci numbers: they are entries of the powers of a \(2\times2\) matrix \(Q\), and powers of one matrix are multiplied like powers of a number, by adding their exponents. Together, these two facts turn the sum of the matrices \(Q^{k+s(k)}\) over all \(k\) below \(2^b\) into a product of \(b\) factors, in the same way as \((1+x)(1+x^2)(1+x^4)\) equals \(1+x+x^2+\dots+x^7\). The numbers from \(0\) to \(10^{18}\) fall into \(25\) blocks, one for each binary digit \(1\) of their count \(10^{18}+1\): the block of the digit \(1\) in position \(b\) consists of \(2^b\) consecutive numbers and can be treated in the same way (Section 5). The whole computation takes \(229\) multiplications of \(2\times2\) matrices whose entries are remainders modulo \(p\). A second method, based on Binet's formula and on numbers of the form \(a+b\sqrt5\), reads the binary digits in the opposite order and checks the result by a different route.

Mathematical Approach

Section 1 looks at the first terms and at the indices \(k+s(k)\), which behave less regularly than one might expect. Section 2 expresses the Fibonacci numbers by powers of a matrix, Sections 3 and 4 prove the product formula for the \(2^b\) numbers from \(0\) to \(2^b-1\), and Section 5 splits an arbitrary range into blocks of this kind. Section 6 explains the computation modulo \(p\), Section 7 the second method, and Section 8 what else the argument gives. A subscript \(2\) marks a number written in binary, as in \(1011_2=11\).

1. The first terms

The table lists the first eleven terms of the sum. Together they give \(369\), the value of \(S(10)\) stated in the problem.

\(k\)\((k)_2\)\(s(k)\)\(k+s(k)\)\(F_{k+s(k)}\)
\(0\)\(0\)\(0\)\(0\)\(0\)
\(1\)\(1\)\(1\)\(2\)\(1\)
\(2\)\(10\)\(1\)\(3\)\(2\)
\(3\)\(11\)\(2\)\(5\)\(5\)
\(4\)\(100\)\(1\)\(5\)\(5\)
\(5\)\(101\)\(2\)\(7\)\(13\)
\(6\)\(110\)\(2\)\(8\)\(21\)
\(7\)\(111\)\(3\)\(10\)\(55\)
\(8\)\(1000\)\(1\)\(9\)\(34\)
\(9\)\(1001\)\(2\)\(11\)\(89\)
\(10\)\(1010\)\(2\)\(12\)\(144\)

The indices \(k+s(k)\) do not increase steadily. Adding \(1\) to a number that ends in exactly \(t\) ones, where \(t\) may be \(0\), turns these ones into zeros and the digit \(0\) immediately to their left into a \(1\), so \(s\) changes by \(1-t\) and \(k+s(k)\) by \(2-t\). The index therefore grows by \(2\) after an even \(k\) and by \(1\) after a \(k\) that ends in exactly one \(1\), it stays the same after a \(k\) that ends in exactly two ones, and it decreases after a \(k\) that ends in three or more. This is why \(k=7=111_2\) gives the index \(10\) and \(k=8\) the smaller index \(9\), while \(k=3\) and \(k=4\) both give \(5\).

The sequence of indices \(0,2,3,5,5,7,8,10,9,11,12,\dots\) is A092391 of the OEIS. [5] Some numbers occur in it more than once, and others not at all. The numbers \(1,4,6,13,15,18,21,\dots\) never occur; they are called binary self numbers or binary Colombian numbers, the base-\(2\) case of the self numbers that D. R. Kaprekar first described in 1959. [6][7] By a comment in the entry A010061, their asymptotic density is about \(0.2527\): among the numbers up to \(n\), the proportion of those that never occur as an index tends to this value as \(n\) grows, so roughly a quarter of all numbers never occur. [6] A number can also occur three times, for the first time \(129\), which equals \(123+s(123)\), \(124+s(124)\) and \(128+s(128)\), and four times, for the first time \(4102\), which is reached from \(k=4091\), \(4092\), \(4099\) and \(4100\). [8] The terms of \(S(N)\) are therefore Fibonacci numbers whose indices skip some numbers, repeat others and sometimes go backwards, and the familiar formula \(F_1+\dots+F_n=F_{n+2}-1\) for a sum of consecutive Fibonacci numbers does not apply. [4] The method below never needs to know which indices occur and how often: the product formula of Section 4 keeps count by itself.

2. Fibonacci numbers as matrix powers

Two \(2\times2\) matrices are multiplied row by column:

$$\begin{aligned}&\begin{pmatrix}a&b\\c&d\end{pmatrix}\begin{pmatrix}e&f\\g&h\end{pmatrix}\\&\quad=\begin{pmatrix}ae+bg&af+bh\\ce+dg&cf+dh\end{pmatrix}.\end{aligned}$$

Let \(I\) be the \(2\times2\) identity matrix, with \(1\) on the diagonal and \(0\) elsewhere, and

$$Q=\begin{pmatrix}1&1\\1&0\end{pmatrix}.$$

Then, for every \(n\ge1\),

$$Q^n=\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}.$$

This formula is well known, [4] and its proof is short. For \(n=1\) the right-hand side is \(Q\) itself, because \(F_2=F_1=1\) and \(F_0=0\). If the formula holds for some \(n\), then

$$Q^nQ=\begin{pmatrix}F_{n+1}+F_n&F_{n+1}\\F_n+F_{n-1}&F_n\end{pmatrix},$$

and by the recurrence the two sums in the left column are \(F_{n+2}\) and \(F_{n+1}\), so the formula holds for \(n+1\) as well. Running the recurrence backwards gives \(F_{-1}=F_1-F_0=1\), and with this value the formula also holds for \(n=0\), where \(Q^0=I\). In every case \(F_n\) is the entry of \(Q^n\) in the first row and the second column. We write \([A]_{12}\) for this entry of a matrix \(A\). The entries of a sum of matrices are the sums of the entries, so

$$S(N)=\Bigl[\sum_{k=0}^{N}Q^{k+s(k)}\Bigr]_{12}.$$

A product of powers of \(Q\) is again a power of \(Q\), \(Q^mQ^n=Q^{m+n}=Q^nQ^m\), so all the matrices that can be built from \(Q\) and \(I\) by addition, subtraction and multiplication commute with each other: \(AB=BA\) for any two of them, although for matrices in general the order of the factors matters. For such matrices, multiplying out a product of sums and collecting equal terms works exactly as it does for numbers. Consequently, every identity between polynomials in a variable \(x\) with integer coefficients remains true when \(x\) is replaced by \(Q\) and every constant \(c\) by \(cI\). Apart from the formula for \(Q^n\), this is the only property of matrix multiplication that the method needs. Moreover \(Q^2=Q+I\), as the formula for \(n=2\) shows, so every such matrix can be reduced to the form

$$aI+bQ=\begin{pmatrix}a+b&b\\b&a\end{pmatrix},$$

for example

$$Q^5=\begin{pmatrix}8&5\\5&3\end{pmatrix}=3I+5Q.$$

All the matrices in the examples below have this shape, with equal entries off the diagonal and an upper left entry equal to the sum of the two entries of the second row, which is a convenient check when following them by hand.

3. The index as a sum over the binary digits

Write a non-negative integer \(k\) in binary as \(k=\sum_{i\ge0}d_i2^i\) with digits \(d_i\) equal to \(0\) or \(1\), all but finitely many of them zero. Then \(s(k)=\sum_{i\ge0}d_i\), and adding the two sums gives

$$k+s(k)=\sum_{i\ge0}d_i\,(2^i+1).$$

A one in position \(i\) is worth \(2^i+1\) instead of \(2^i\). For example, \(13=1101_2\) has its ones in the positions \(3\), \(2\) and \(0\), and \(13+s(13)=16=9+5+2\). The numbers \(2^i+1\) are \(2,3,5,9,17,33,\dots\), and the indices \(k+s(k)\) are exactly the sums of distinct numbers from this list; this is also how A010061 describes the binary self numbers, as the numbers that are not such sums. [6] The index \(5\) occurs twice because \(2+3\) and \(5\) are two different ways of writing it as such a sum. For powers of \(Q\), the formula says that

$$Q^{k+s(k)}=\prod_{i\,:\,d_i=1}R_i,$$

a product with one factor \(R_i=Q^{2^i+1}\) for each digit \(1\) of \(k\). For \(k=0\) the product is empty and equals \(I\).

4. A full block

For \(b\ge0\), the numbers \(k\) with \(0\le k\lt2^b\) are those whose binary digits vanish from position \(b\) on. For each such \(b\),

$$\sum_{k=0}^{2^b-1}x^{k+s(k)}=\prod_{i=0}^{b-1}\bigl(1+x^{2^i+1}\bigr).$$

To see this, multiply out the right-hand side. Each term of the expansion chooses, in every factor \(1+x^{2^i+1}\), either \(1\) or \(x^{2^i+1}\); write \(d_i=0\) or \(d_i=1\) for this choice. The term is then the power of \(x\) with the exponent \(\sum_{i\lt b}d_i\,(2^i+1)\), which by Section 3 is \(k+s(k)\) for the number \(k=\sum_{i\lt b}d_i2^i\). Every choice gives a number \(k\) with \(0\le k\lt2^b\), and every such number arises from exactly one choice, because the binary representation of a number is unique. So the expansion consists of exactly one term \(x^{k+s(k)}\) for each \(k\) in the range, and this is the left-hand side. For \(b=0\) both sides equal \(1\): the product is empty, and the sum has the single term with \(k=0\). The same argument with \(x^{2^i}\) in place of \(x^{2^i+1}\) gives the familiar identity

$$\prod_{i=0}^{b-1}\bigl(1+x^{2^i}\bigr)=\sum_{k=0}^{2^b-1}x^k,$$

and the formula above is the same identity with every power of two increased by one.

For \(b=3\), for example,

$$\begin{aligned}&(1+x^2)(1+x^3)(1+x^5)\\&\quad=1+x^2+x^3+2x^5\\&\qquad+x^7+x^8+x^{10},\end{aligned}$$

and the exponents, with \(5\) counted twice, are the indices in the first eight rows of the table. The coefficients \(1,0,1,1,0,2,0,1,1,0,1\) of \(x^0,x^1,\dots,x^{10}\) read the same in both directions, and this is true for every \(b\): replacing each digit \(d_i\) by \(1-d_i\) turns \(k\) into \(2^b-1-k\) and \(s(k)\) into \(b-s(k)\), so the index \(e=k+s(k)\) becomes \(2^b+b-1-e\), and the indices \(e\) and \(2^b+b-1-e\) occur equally often in a block.

By Section 2 we may put \(Q\) for \(x\) and \(I\) for \(1\). With

$$D_b=\prod_{i=0}^{b-1}(I+R_i)$$

this gives

$$D_b=\sum_{k=0}^{2^b-1}Q^{k+s(k)},$$

and therefore

$$[D_b]_{12}=\sum_{k=0}^{2^b-1}F_{k+s(k)}.$$

The matrices \(D_b\) are built one factor at a time, from \(D_0=I\) and \(D_{b+1}=D_b\,(I+R_b)\). The first three steps are

$$D_1=I+Q^2=\begin{pmatrix}3&1\\1&2\end{pmatrix},$$

$$D_2=D_1\,(I+Q^3)=\begin{pmatrix}14&8\\8&6\end{pmatrix},$$

$$\begin{aligned}D_3&=D_2\,(I+Q^5)\\&=\begin{pmatrix}166&102\\102&64\end{pmatrix},\end{aligned}$$

with \(I+Q^3=\begin{pmatrix}4&2\\2&2\end{pmatrix}\) and \(I+Q^5=\begin{pmatrix}9&5\\5&4\end{pmatrix}\), and indeed \([D_1]_{12}=1=F_0+F_2\), \([D_2]_{12}=8=0+1+2+5\) and \([D_3]_{12}=102\), the sum of the first eight terms in the table. The block sums \([D_b]_{12}\) for \(b=0,1,\dots,6\) are \(0\), \(1\), \(8\), \(102\), \(7888\), \(28\,177\,452\) and \(222\,072\,053\,510\,048\); they grow very fast, because the largest index in a block of \(2^b\) numbers is \(2^b+b-1\).

5. Any upper limit

Let \(M=N+1\), so that the terms of \(S(N)\) are those with \(0\le k\lt M\), and write \(M_i\) for the binary digit of \(M\) in position \(i\). Take such a \(k\) and compare its digits with those of \(M\), starting from the highest position. Since \(k\lt M\), there is a highest position \(b\) at which they differ, and there \(M\) has the digit \(1\) and \(k\) the digit \(0\); above \(b\) the digits agree, and below \(b\) the digits of \(k\) can be anything. Conversely, if \(M_b=1\), then every number that agrees with \(M\) above position \(b\), has the digit \(0\) in position \(b\) and has arbitrary digits below it is smaller than \(M\). So the numbers \(0,1,\dots,N\) fall into blocks, one for each digit \(1\) of \(M\), and no number lies in two blocks, because \(k\) determines the position \(b\). The block of the digit \(1\) in position \(b\) consists of the \(2^b\) numbers \(H_b+j\) with \(0\le j\lt2^b\), where \(H_b\) has the digits of \(M\) above position \(b\) and zeros everywhere else.

In \(H_b+j\), the ones of \(H_b\) lie above position \(b\) and those of \(j\) below it, so the addition produces no carries, \(s(H_b+j)=s(H_b)+s(j)\), and

$$\begin{aligned}&(H_b+j)+s(H_b+j)\\&=\bigl(H_b+s(H_b)\bigr)+\bigl(j+s(j)\bigr).\end{aligned}$$

The block therefore contributes \(Q^{H_b+s(H_b)}\) times the sum of the powers \(Q^{j+s(j)}\) over \(0\le j\lt2^b\), which is \(D_b\). By Section 3, \(Q^{H_b+s(H_b)}\) is the product of the factors \(R_i\) over the digits \(1\) of \(M\) above position \(b\); we call it the prefactor \(P_b\) of the block. Altogether,

$$S(N)=\Bigl[\sum_{b\,:\,M_b=1}P_bD_b\Bigr]_{12},$$

where

$$P_b=\prod_{i\gt b\,:\,M_i=1}R_i.$$

For \(N=10\) we have \(M=11=1011_2\), with ones in the positions \(3\), \(1\) and \(0\). The block of position \(3\) is \(k=0,\dots,7\), with \(P_3=I\), and it contributes \([D_3]_{12}=102\). The block of position \(1\) is \(k=8,9\), with \(H_1=8\) and \(P_1=R_3=Q^9\), and it contributes \([Q^9(I+Q^2)]_{12}\), which is \(F_9+F_{11}=34+89=123\). The block of position \(0\) is \(k=10\) alone, with \(H_0=10=1010_2\) and \(P_0=R_3R_1=Q^9Q^3=Q^{12}\), and it contributes \(F_{12}=144\). The total is \(102+123+144=369\).

For \(N=50\), \(M=51=110011_2\) has ones in the positions \(5\), \(4\), \(1\) and \(0\), and the blocks are \(k=0,\dots,31\), then \(k=32,\dots,47\), then \(k=48,49\) and finally \(k=50\). Their prefactors are \(P_5=I\), \(P_4=R_5=Q^{33}\), \(P_1=R_5R_4=Q^{50}\) and \(P_0=R_5R_4R_1=Q^{53}\), and their contributions are \(28\,177\,452\), \(62\,170\,214\,984\), \(F_{50}+F_{52}=45\,537\,549\,124\) and \(F_{53}=53\,316\,291\,173\). Their sum is \(161\,052\,232\,733\), the given value of \(S(50)\).

Going down through the digits \(1\) of \(M\), each prefactor is the previous one multiplied by one more factor \(R_i\), so the whole sum is computed in a single pass over the digits of \(M\) from the highest position down. A running product \(P\) starts as \(I\); at each position \(b\) with \(M_b=1\), the product \(P\,D_b\) is added to the total, and then \(P\) is multiplied by \(R_b\). For \(N=10^{18}\), \(M=10^{18}+1\) lies between \(2^{59}\) and \(2^{60}\), so it has \(60\) binary digits; \(25\) of them are ones, and the sum consists of \(25\) blocks.

6. Computing modulo p

The remainder of a sum or a product modulo \(p\) depends only on the remainders of the terms or factors. So every entry may be replaced by its remainder after each addition and each multiplication, and the upper right entry of the result is then the remainder of \(S(N)\). The remainders are smaller than \(p\lt2^{30}\), the product of two of them is smaller than \(2^{60}\), and the sum of two such products, as it occurs in an entry of a matrix product, is smaller than \(2^{61}\); so \(64\)-bit integers suffice, although the C++ program forms the products with \(128\) bits. Nothing in the matrix method uses that \(p\) is a prime.

The factors \(R_i=Q^{2^i+1}\) are obtained by repeated squaring, \(Q^{2^{i+1}}=(Q^{2^i})^2\) and \(R_i=Q^{2^i}Q\), a case of the method known as exponentiation by squaring. [9] Together with \(D_{i+1}=D_i\,(I+R_i)\), this preparation, as the program carries it out, takes three matrix multiplications for each binary digit of \(M\), except that the square after the last digit is skipped: \(179\) multiplications for \(N=10^{18}\). The pass over the digits takes two more for each of the \(25\) digits \(1\), which makes \(229\) multiplications of \(2\times2\) matrices in all, each consisting of eight multiplications of remainders; a few of them, such as the one that yields \(D_{60}\) and the last update of \(P\), are not needed for the result.

7. Binet's formula: a second method

Let \(\varphi=\frac{1+\sqrt5}{2}\) and \(\psi=\frac{1-\sqrt5}{2}\) be the two roots of \(x^2=x+1\). Binet's formula

$$F_n=\frac{\varphi^n-\psi^n}{\sqrt5}$$

expresses the Fibonacci numbers by powers, [4] and with powers the index \(k+s(k)\) splits over the binary digits again. A form that is better suited to computation follows from \(\varphi^2=\varphi+1\): by induction, \(\varphi^n=F_n\varphi+F_{n-1}\) for \(n\ge1\), exactly as in Section 2, [4] and for \(n=0\) the same holds with \(F_{-1}=1\). Inserting \(\varphi=\frac12+\frac12\sqrt5\) gives

$$\varphi^n=\Bigl(\frac{F_n}{2}+F_{n-1}\Bigr)+\frac{F_n}{2}\sqrt5,$$

so \(F_n\) is twice the coefficient of \(\sqrt5\) in \(\varphi^n\). Summing over \(k\): if

$$\sum_{k=0}^{N}\varphi^{k+s(k)}=U+V\sqrt5$$

with rational numbers \(U\) and \(V\), which are unique because \(\sqrt5\) is irrational, then \(S(N)=2V\).

Modulo \(p\), we work with pairs of remainders \(a\) and \(b\), written \(a+b\sqrt5\), where \(\sqrt5\) is now just a symbol whose square counts as \(5\), in the same way as the square of the imaginary unit counts as \(-1\). The pairs are added component by component and multiplied by the rule

$$\begin{aligned}&(a+b\sqrt5)(c+d\sqrt5)\\&\quad=(ac+5bd)+(ad+bc)\sqrt5.\end{aligned}$$

This multiplication is commutative and associative and distributes over the addition, because it is the multiplication of the polynomials \(a+b\alpha\) and \(c+d\alpha\) in a variable \(\alpha\), followed by replacing \(\alpha^2\) with \(5\). Since \(p\) is odd, \(2\cdot\frac{p+1}{2}=p+1\equiv1\) modulo \(p\), so \(\frac{p+1}{2}=500\,000\,004\) plays the role of \(\frac12\); \(\varphi\) becomes the pair with \(a=b=500\,000\,004\), and \(\varphi^2=\varphi+1\) holds for this pair as well. The derivation of \(\varphi^n=F_n\varphi+F_{n-1}\) and of the coefficient \(\frac{F_n}{2}\) used only these rules of calculation and \(\varphi^2=\varphi+1\), so \(S(N)\) is congruent to \(2V\) modulo \(p\) when the sum of the powers is computed with such pairs. As an aside that the method does not need: \(5\) has no square root modulo \(p\). By Euler's criterion this is equivalent to \(5^{(p-1)/2}\equiv-1\) modulo \(p\), which can be checked directly, [10] and by quadratic reciprocity it follows from \(p\equiv2\) modulo \(5\): an odd prime \(p\ne5\) has \(5\) as a square exactly when \(p\equiv\pm1\) modulo \(5\). [11] The pairs therefore even form a field with \(p^2\) elements, in which every pair other than \(0\) has an inverse; this is exactly the construction in the reference. [12]

The sum of the powers \(\varphi^{k+s(k)}\) is computed by a recursion that reads the binary digits from the lowest one upwards. For a pair \(x\) and an integer \(n\ge0\) let

$$T(n,x)=\sum_{k=0}^{n}x^k\varphi^{s(k)},$$

so that the sum we need is \(T(N,\varphi)\). For odd \(n=2q+1\), take the terms with \(k=2j\) and \(k=2j+1\) together, where \(0\le j\le q\). Since \(s(2j)=s(j)\) and \(s(2j+1)=s(j)+1\), these two terms contribute

$$\begin{aligned}&x^{2j}\varphi^{s(j)}+x^{2j+1}\varphi^{s(j)+1}\\&\quad=(1+x\varphi)\,(x^2)^j\varphi^{s(j)},\end{aligned}$$

and the sum over \(j\) gives

$$\begin{aligned}&T(2q+1,x)\\&\quad=(1+x\varphi)\,T(q,x^2).\end{aligned}$$

For even \(n\ge2\) the last term is split off: \(T(n,x)\) equals \(T(n-1,x)+x^n\varphi^{s(n)}\), and \(T(0,x)=1\). An odd step halves \(n\), rounding down, and an even step makes \(n\) odd, so the recursion ends after at most about \(2\log_2N\) steps; each even step computes two powers by squaring. For \(N=10\), for example,

$$\begin{aligned}T(10,\varphi)&=T(9,\varphi)+\varphi^{10}\varphi^2,\\T(9,\varphi)&=(1+\varphi^2)\,T(4,\varphi^2),\\T(4,\varphi^2)&=T(3,\varphi^2)+\varphi^8\varphi,\\T(3,\varphi^2)&=(1+\varphi^3)\,T(1,\varphi^4),\\T(1,\varphi^4)&=(1+\varphi^5)\,T(0,\varphi^8),\end{aligned}$$

so that

$$\begin{aligned}&T(10,\varphi)\\&\quad=(1+\varphi^2)(1+\varphi^3)(1+\varphi^5)\\&\qquad+(1+\varphi^2)\,\varphi^9+\varphi^{12}.\end{aligned}$$

This is the block formula of Section 5 for \(N=10\), with \(\varphi\) in place of \(Q\), and multiplying out gives the powers of \(\varphi\) with the exponents \(0,2,3,5,5,7,8,10\), then \(9,11\) and finally \(12\), which are the indices of the table. The same happens for every \(N\). Write \(n_j\) for the value of \(n\) on reaching the depth \(j\), that is, after \(j\) halvings. Then \(n_j+1\) is \(M=N+1\) with its last \(j\) binary digits removed, so \(n_j\) is even exactly when \(M_j=1\). At every depth \(j\) other than that of the highest digit of \(M\) there is exactly one odd step, and it multiplies by \(1+\varphi^{2^j+1}\), the factor of position \(j\) in the products \(D_b\). If moreover \(M_j=1\), the even step at this depth splits off the term \(x^{n_j}\varphi^{s(n_j)}\) with \(x=\varphi^{2^j}\) and adds it to the result of the odd step, so this term is not multiplied by the factor of position \(j\). In this case \(n_j\) consists of the digits of \(M\) above position \(j\) followed by a \(0\), so \(2^jn_j=H_j\) and \(s(n_j)=s(H_j)\), and the term equals \(\varphi^{H_j+s(H_j)}\). As the calls return, it is multiplied by the factors of the depths \(0,1,\dots,j-1\) and becomes the contribution \(P_jD_j\) of the block of position \(j\) in Section 5. Likewise, the value \(1\) returned by the final call with \(n=0\) is multiplied by the factors of all the other depths and becomes the contribution of the block of the highest digit of \(M\). The recursion therefore evaluates the same block formula as Section 5, but it reads the digits of \(M\) in the opposite order, from the lowest digit upwards; it computes each prefactor directly, as the product of the two powers \(x^{n_j}\) and \(\varphi^{s(n_j)}\), instead of as a running product, and it uses pairs instead of matrices. In the program, the code of the two methods shares only the arithmetic of remainders. For \(N=10^{18}\) the recursion makes \(84\) calls: \(59\) odd steps, \(24\) even steps, one for each digit \(1\) of \(M\) below the highest, and the final call.

8. Other sums of the same kind

The argument uses only two facts: \(k+s(k)\) is a sum over the binary digits of \(k\) of terms that depend on the position and the digit alone, and Fibonacci numbers are entries of the powers of one matrix. With \(R_i=Q^{a2^i+c}\) it therefore gives the sum of \(F_{ak+cs(k)}\) for any fixed non-negative integers \(a\) and \(c\), and, with the companion matrix of a linear recurrence with constant coefficients in place of \(Q\) and a fixed linear combination of the entries of the summed matrix in place of the single entry \([\,\cdot\,]_{12}\), the corresponding sums for any sequence that satisfies such a recurrence. In base \(B\), with \(s_B(k)\) the sum of the digits, a digit \(d\) in position \(i\) contributes \(d\,(B^i+1)\) to \(k+s_B(k)\); the factor of position \(i\) in the product formula becomes \(1+y+y^2+\dots+y^{B-1}\) with \(y=x^{B^i+1}\), and a range splits into at most \(B-1\) blocks for each digit of \(M\).

How the Code Works

The C++ program [13] implements the matrix method of Sections 2 to 6, the method of Section 7 and a direct summation, and compares them in its self-test. It works with unsigned \(64\)-bit integers; its constants are MOD (the prime \(p\)), TARGET (the value \(10^{18}\)) and MAX_LIMIT (the value \(2^{64}-2\), the largest \(N\) for which \(N+1\) still fits into \(64\) bits). require(condition, description) throws an exception with the description when a check fails.

Two small structures supply the arithmetic of the entries. Modular works with remainders: add subtracts \(p\) once when the sum reaches \(p\), and multiply forms the product with \(128\) bits, as unsigned __int128, before reducing it. Exact works with exact \(128\)-bit integers and serves for small \(N\) only; its add and multiply use __builtin_add_overflow and __builtin_mul_overflow and fail through require instead of silently wrapping around. The template Matrix<Ring> stores the four entries in entry, provides zero(), identity() and fibonacci() (the matrix \(Q\)), and defines + and * using only the add and multiply of its Ring. power(base, exponent) computes a power by squaring, and it squares only while bits of the exponent remain.

modified_sum<Ring>(limit) is the method of Sections 4 to 6. It sets count to \(N+1\), the number \(M\), and bits to std::bit_width(count), the number of binary digits of \(M\). In a loop over \(i=0,1,\dots\) it computes shifted, the product of square and \(Q\), which is \(R_i\), appends the product of block.back() and \(I+R_i\) to block, which starts with \(D_0=I\) and thus receives \(D_1,D_2,\dots\), and appends \(R_i\) to factor; square holds \(Q^{2^i}\) and is squared for the next round, except after the last one. A second loop runs bit from bits - 1 down to \(0\) and, at each position where count has the digit \(1\), adds the product of prefix and block[bit] to total and then multiplies prefix by factor[bit]. The result is total.entry[0][1], the entry \([\,\cdot\,]_{12}\), since C++ numbers rows and columns from \(0\). modified_sum never forms the exponent \(H_b+s(H_b)\) itself, which for \(N\) close to \(2^{64}\) would not fit into \(64\) bits; it multiplies the factors \(R_i\) instead.

Quadratic holds the pair a, b for \(a+b\sqrt5\) modulo \(p\), with + and * as in Section 7, the products again formed with \(128\) bits, and power raises such a pair to a power by squaring. weighted_sum(limit, base, phi) is the recursion for \(T(n,x)\) with \(n\) = limit and \(x\) = base. binet_sum(limit) sets phi to the pair whose two components are both HALF, which is \(\frac{p+1}{2}\), calls weighted_sum(limit, phi, phi) and returns twice the coefficient of \(\sqrt5\), computed as Modular::add(total.b, total.b).

brute_force_prefixes<Ring>(limit) computes \(F_0,F_1,\dots,F_{L+64}\) for \(L\) = limit by the recurrence, in the arithmetic of its Ring, and returns the list of the values \(S(0),S(1),\dots,S(L)\) obtained by direct summation; the margin of \(64\) is more than enough, since a \(32\)-bit \(k\) has at most \(32\) ones. run_tests, started with --self-test, requires \(S(10)=369\) and \(S(50)=161\,052\,232\,733\) from the exact matrix method and from exact direct summation, and their remainders from the matrix method and from the method of Section 7 modulo \(p\); it compares the exact matrix method with exact direct sums for every \(N\le100\), and both methods modulo \(p\) with direct sums for every \(N\le4096\) and at the twelve values \(0\), \(1\), \(2\), \(7\), \(8\), \(15\), \(16\), \(31\), \(32\), \(1000\), \(123\,456\) and \(1\,000\,000\), which include block boundaries. At \(N=10^{18}\) it requires both methods to agree and \(S(N)-S(N-1)\) to agree modulo \(p\) with \(F_{N+s(N)}\), computed as one power of \(Q\), and it requires both methods to agree at MAX_LIMIT. Without an argument the program prints \(S(10^{18})\) modulo \(p\); with a decimal argument \(N\) from \(0\) to \(2^{64}-2\) it prints \(S(N)\) modulo \(p\).

The Python and Java versions follow the C++ program function by function, with the same command line and the same self-test. Python passes the arithmetic as a class with the static methods add and multiply, represents a matrix as a pair of rows and \(a+b\sqrt5\) as a pair of integers, and needs no overflow check in Exact, because its integers are unbounded. Java uses an interface Ring with the implementations MODULAR, on Long, and EXACT, on BigInteger; it multiplies remainders in long, which holds products below \(2^{60}\), and it stores \(N\) as an unsigned \(64\)-bit number in a long, handled with Long.compareUnsigned, the shift >>> and Long.parseUnsignedLong.

Complexity and Verification

The matrix method takes \(O(\log N)\) multiplications of \(2\times2\) matrices, at most three for each binary digit of \(N+1\) and two more for each digit \(1\), \(229\) for \(N=10^{18}\), and since every product of two remainders is reduced before it is added, no number it handles reaches \(2^{60}\). The method of Section 7 takes \(O((\log N)^2)\) multiplications of pairs, because each even step computes two powers by squaring; for \(N=10^{18}\) it calls weighted_sum \(84\) times and computes \(48\) powers. Direct summation takes about \(2N\) additions, \(N+63\) for the Fibonacci numbers and \(N+1\) for the sum, and is used only up to \(N=10^6\). Measured as the median wall-clock time of five runs of the whole program on an Apple M4 Max, the C++ program built with clang++ -std=c++20 -O3 prints the answer in about \(0.002\) seconds, the Java version, compiled beforehand and run on OpenJDK 17, in about \(0.03\) seconds, and the Python version on CPython 3.11 in about \(0.02\) seconds; nearly all of this is the start of the process. Their self-tests take about \(0.013\), \(0.09\) and \(0.56\) seconds.

All three programs print the same value and pass their self-tests, and the numbers derived by hand in this article agree with them modulo \(p\): the eleven terms in the table, the block sums of Section 4, and the decompositions of \(S(10)\) and \(S(50)\) in Section 5.

Further checks, which are not part of the published solutions, use different code. A second C++ program represents every polynomial in \(Q\) by the two numbers \(a\) and \(b\) of the form \(aI+bQ\) from Section 2, multiplies them by the rule that \((aI+bQ)(cI+dQ)\) equals \((ac+bd)I+(ad+bc+bd)Q\), which follows from \(Q^2=Q+I\), and evaluates the block formula of Section 5 in this representation; for every \(N\) below \(2^{24}\), this program and the function modified_sum of the published program agree with direct summation modulo \(p\). A second evaluation in the same representation computes each block separately, with \(P_b\) as the product of the two powers \(Q^{H_b}\) and \(Q^{s(H_b)}\), because \(H_b+s(H_b)\) can exceed \(2^{64}-1\), and with \(D_b\) from powers of \(Q\); it agrees with direct summation for every \(N\) below \(2^{16}\), and all three agree at the \(190\) values \(0\), \(1\), \(2\), \(2^j-1\), \(2^j\), \(2^j+1\) for \(2\le j\le63\) and \(2^{64}-2\), and at \(100\,000\) pseudo-random values of \(N\) below \(2^{64}-1\). A Python script compares exact big-integer evaluations of the block formula with exact direct sums for every \(N\le2000\), and checks the product formula of Section 4 for every \(b\le20\) by comparing the coefficients of the product with the number of \(k\) below \(2^b\) for each value of \(k+s(k)\); it also recomputes, with exact integers, the block sums of Section 4, the matrix \(D_3\) and the four contributions to \(S(50)\). The facts quoted from the OEIS in Section 1 were recomputed as well: among the numbers below \(2^{20}\), the first indices that occur two, three and four times are \(5\), \(129\) and \(4102\), and the proportion of numbers that never occur is \(0.2527\) to four decimal places.

Footnotes and References

The references below supply background facts. The product formula, the splitting into blocks and the recursion of Section 7 are derived explicitly in this article.

  1. Project Euler 1020 — Modified Sum of Fibonacci Numbers. The official statement: the Fibonacci numbers are defined by \(F_0=0\), \(F_1=1\) and \(F_k=F_{k-1}+F_{k-2}\) for \(k\ge2\), \(s(k)\) is the number of ones in the binary representation of \(k\), \(S(N)\) is the sum of \(F_{k+s(k)}\) for \(k=0,\dots,N\), \(S(10)=369\) and \(S(50)=161\,052\,232\,733\) are given, and \(S(10^{18})\) is asked for modulo \(10^9+7\).
  2. Wikipedia — Hamming weight. The Hamming weight of a string is the number of its symbols that differ from the zero symbol; for the binary representation of a number it is the number of ones, also called the population count, popcount, sideways sum or bit summation.
  3. OEIS A000120. The ones-counting sequence: the number of ones in the binary expansion of \(n\), also called the binary weight or the Hamming weight of \(n\), \(0,1,1,2,1,2,2,3,1,\dots\) for \(n=0,1,2,\dots\).
  4. Wikipedia — Fibonacci sequence. The article starts the sequence with \(F_0=0\) and \(F_1=1\), gives Binet's formula with \(\varphi=\frac{1+\sqrt5}{2}\) and \(\psi=\frac{1-\sqrt5}{2}\), the decomposition \(\varphi^n=F_n\varphi+F_{n-1}\) with its proof by induction, the matrix form \(Q^n=\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}\), which it notes can be computed with \(O(\log n)\) arithmetic operations by exponentiation by squaring, and the identity \(F_1+\dots+F_n=F_{n+2}-1\). It also states that the number of decimal digits of \(F_n\) is asymptotic to \(n\log_{10}\varphi\approx0.2090\,n\).
  5. OEIS A092391. The sequence \(n+\mathrm{wt}(n)\), where \(\mathrm{wt}(n)\) is the binary weight of \(n\): \(0,2,3,5,5,7,8,10,9,\dots\) for \(n=0,1,2,\dots\). The entry refers to A010061 for the numbers that do not occur in it and to A228085 for the number of times a number occurs.
  6. OEIS A010061. The binary self or Colombian numbers, \(1,4,6,13,15,18,21,\dots\): the numbers that cannot be expressed as a sum of distinct terms of the form \(2^k+1\) with \(k\ge0\), or equivalently the numbers not of the form \(m\) plus the sum of the binary digits of \(m\). A comment in the entry gives their asymptotic density as \(0.252660\dots\).
  7. Wikipedia — Self number. A self number in a given base is a natural number that cannot be written as the sum of a natural number and the digits of that number; the article says that D. R. Kaprekar first described these numbers in 1959, gives the base-\(10\) self numbers \(1,3,5,7,9,20,31,\dots\), and refers to A010061 for the base-\(2\) self numbers.
  8. OEIS A228085. The number of distinct \(k\) with \(n=k+\mathrm{wt}(k)\). Its comments state that the value \(2\) occurs first at \(n=5\), the value \(3\) at \(n=129\), from \(k=123\), \(124\) and \(128\), and the value \(4\) at \(n=4102\), from \(k=4091\), \(4092\), \(4099\) and \(4100\).
  9. Wikipedia — Exponentiation by squaring. A general method for computing large positive integer powers of a number, or more generally of an element of a semigroup such as a square matrix; variants of it are known as square-and-multiply or binary exponentiation.
  10. Wikipedia — Legendre symbol. For an odd prime \(p\), the Legendre symbol records whether \(a\) is a square modulo \(p\), and by Euler's criterion it is congruent to \(a^{(p-1)/2}\) modulo \(p\).
  11. Wikipedia — Quadratic reciprocity. In a motivating example, the article states that, apart from \(p=2\) and \(p=5\), the number \(5\) is a quadratic residue modulo a prime \(p\) exactly when \(p\) is a quadratic residue modulo \(5\), that is, when \(p\equiv1\) or \(p\equiv4\) modulo \(5\).
  12. Wikipedia — Finite field. The section on \(\mathrm{GF}(p^2)\) for an odd prime \(p\) constructs this field from a quadratic non-residue \(r\) modulo \(p\): its elements are the expressions \(a+b\alpha\) with \(\alpha^2=r\), and they are multiplied by the rule that \((a+b\alpha)(c+d\alpha)\) equals \((ac+rbd)+(ad+bc)\alpha\).
  13. C++ — Euler1020.cpp. The linked immutable C++ revision contains Modular, Exact, Matrix, modified_sum, Quadratic, weighted_sum, binet_sum, brute_force_prefixes and the checks run by --self-test. It is the implementation record for this article.

Problem 1020 source code

C++

#include <array>
#include <bit>
#include <charconv>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <system_error>
#include <vector>

namespace {

using u64 = std::uint64_t;
using u128 = unsigned __int128;

constexpr u64 MOD = 1'000'000'007;
constexpr u64 TARGET = 1'000'000'000'000'000'000;
constexpr u64 MAX_LIMIT = std::numeric_limits<u64>::max() - 1;

void require(const bool condition, const char* description) {
    if (!condition) throw std::runtime_error(std::string("Check failed: ") + description);
}

struct Modular {
    using Value = u64;

    static Value add(const Value a, const Value b) {
        const Value sum = a + b;
        return sum >= MOD ? sum - MOD : sum;
    }

    static Value multiply(const Value a, const Value b) {
        return static_cast<Value>(static_cast<u128>(a) * b % MOD);
    }
};

struct Exact {
    using Value = u128;

    static Value add(const Value a, const Value b) {
        Value sum;
        require(!__builtin_add_overflow(a, b, &sum), "exact sum fits in 128 bits");
        return sum;
    }

    static Value multiply(const Value a, const Value b) {
        Value product;
        require(!__builtin_mul_overflow(a, b, &product), "exact product fits in 128 bits");
        return product;
    }
};

template <typename Ring>
struct Matrix {
    using Value = typename Ring::Value;
    std::array<std::array<Value, 2>, 2> entry;

    static Matrix zero() { return {{{{0, 0}, {0, 0}}}}; }
    static Matrix identity() { return {{{{1, 0}, {0, 1}}}}; }
    static Matrix fibonacci() { return {{{{1, 1}, {1, 0}}}}; }

    Matrix operator+(const Matrix& other) const {
        Matrix result{};
        for (unsigned i = 0; i < 2; ++i) {
            for (unsigned j = 0; j < 2; ++j) result.entry[i][j] = Ring::add(entry[i][j], other.entry[i][j]);
        }
        return result;
    }

    Matrix operator*(const Matrix& other) const {
        Matrix result{};
        for (unsigned i = 0; i < 2; ++i) {
            for (unsigned j = 0; j < 2; ++j) {
                result.entry[i][j] = Ring::add(Ring::multiply(entry[i][0], other.entry[0][j]),
                                               Ring::multiply(entry[i][1], other.entry[1][j]));
            }
        }
        return result;
    }
};

template <typename Ring>
Matrix<Ring> power(Matrix<Ring> base, u64 exponent) {
    auto result = Matrix<Ring>::identity();
    while (exponent != 0) {
        if ((exponent & 1) != 0) result = result * base;
        exponent >>= 1;
        if (exponent != 0) base = base * base;
    }
    return result;
}

template <typename Ring>
typename Ring::Value modified_sum(const u64 limit) {
    using M = Matrix<Ring>;
    require(limit <= MAX_LIMIT, "N + 1 fits in 64 bits");
    const u64 count = limit + 1;
    const unsigned bits = static_cast<unsigned>(std::bit_width(count));
    std::vector<M> factor, block{M::identity()};
    M square = M::fibonacci();
    for (unsigned i = 0; i < bits; ++i) {
        const M shifted = square * M::fibonacci();
        block.push_back(block.back() * (M::identity() + shifted));
        factor.push_back(shifted);
        if (i + 1 < bits) square = square * square;
    }
    M total = M::zero();
    M prefix = M::identity();
    for (unsigned bit = bits; bit-- > 0;) {
        if (((count >> bit) & 1) != 0) {
            total = total + prefix * block[bit];
            prefix = prefix * factor[bit];
        }
    }
    return total.entry[0][1];
}

struct Quadratic {
    u64 a, b;
};

Quadratic operator+(const Quadratic& x, const Quadratic& y) {
    return {Modular::add(x.a, y.a), Modular::add(x.b, y.b)};
}

Quadratic operator*(const Quadratic& x, const Quadratic& y) {
    const u128 a = static_cast<u128>(x.a) * y.a + 5 * (static_cast<u128>(x.b) * y.b);
    const u128 b = static_cast<u128>(x.a) * y.b + static_cast<u128>(x.b) * y.a;
    return {static_cast<u64>(a % MOD), static_cast<u64>(b % MOD)};
}

Quadratic power(Quadratic base, u64 exponent) {
    Quadratic result{1, 0};
    while (exponent != 0) {
        if ((exponent & 1) != 0) result = result * base;
        exponent >>= 1;
        if (exponent != 0) base = base * base;
    }
    return result;
}

Quadratic weighted_sum(const u64 limit, const Quadratic& base, const Quadratic& phi) {
    if (limit == 0) return {1, 0};
    if ((limit & 1) != 0) return (Quadratic{1, 0} + base * phi) * weighted_sum(limit / 2, base * base, phi);
    return weighted_sum(limit - 1, base, phi) + power(base, limit) * power(phi, std::popcount(limit));
}

u64 binet_sum(const u64 limit) {
    constexpr u64 HALF = (MOD + 1) / 2;
    const Quadratic phi{HALF, HALF};
    const Quadratic total = weighted_sum(limit, phi, phi);
    return Modular::add(total.b, total.b);
}

template <typename Ring>
std::vector<typename Ring::Value> brute_force_prefixes(const unsigned limit) {
    std::vector<typename Ring::Value> fibonacci(limit + 65), prefixes;
    fibonacci[1] = 1;
    for (std::size_t i = 2; i < fibonacci.size(); ++i) fibonacci[i] = Ring::add(fibonacci[i - 1], fibonacci[i - 2]);
    typename Ring::Value total = 0;
    for (unsigned k = 0; k <= limit; ++k) {
        total = Ring::add(total, fibonacci[k + static_cast<unsigned>(std::popcount(k))]);
        prefixes.push_back(total);
    }
    return prefixes;
}

void run_tests() {
    require(modified_sum<Exact>(10) == 369, "given S(10), matrix product");
    require(modified_sum<Modular>(10) == 369, "given S(10) modulo the prime");
    require(binet_sum(10) == 369, "given S(10), Binet method");
    const u128 s50 = 161'052'232'733;
    require(modified_sum<Exact>(50) == s50, "given S(50), matrix product");
    require(modified_sum<Modular>(50) == s50 % MOD, "given S(50) modulo the prime");
    require(binet_sum(50) == s50 % MOD, "given S(50), Binet method");

    const auto exact = brute_force_prefixes<Exact>(100);
    require(exact[10] == 369 && exact[50] == s50, "given values by direct summation");
    for (unsigned limit = 0; limit <= 100; ++limit) {
        require(modified_sum<Exact>(limit) == exact[limit], "exact sums for every N up to 100");
    }
    const auto prefixes = brute_force_prefixes<Modular>(1'000'000);
    for (unsigned limit = 0; limit <= 4096; ++limit) {
        require(modified_sum<Modular>(limit) == prefixes[limit], "matrix product for every N up to 4096");
        require(binet_sum(limit) == prefixes[limit], "Binet method for every N up to 4096");
    }
    for (const unsigned limit : {0u, 1u, 2u, 7u, 8u, 15u, 16u, 31u, 32u, 1000u, 123'456u, 1'000'000u}) {
        require(modified_sum<Modular>(limit) == prefixes[limit], "matrix product against direct summation");
        require(binet_sum(limit) == prefixes[limit], "Binet method against direct summation");
    }

    const u64 answer = modified_sum<Modular>(TARGET);
    require(answer == binet_sum(TARGET), "both methods at N = 10^18");
    const u64 step = Modular::add(answer, MOD - modified_sum<Modular>(TARGET - 1));
    const u64 last = power(Matrix<Modular>::fibonacci(), TARGET + std::popcount(TARGET)).entry[0][1];
    require(step == last, "S(N) - S(N - 1) = F(N + s(N)) at N = 10^18");
    require(modified_sum<Modular>(MAX_LIMIT) == binet_sum(MAX_LIMIT), "both methods at the largest N");
    std::cout << "All checks passed: S(10) and S(50), exact sums for N up to 100, direct sums for every N up to 4096 "
                 "and at 12 values up to 1000000, the Binet method, the last term at N = 10^18 and both methods at the "
                 "largest N.\n";
}

}

int main(int argc, char* argv[]) {
    try {
        if (argc == 2 && std::string(argv[1]) == "--self-test") {
            run_tests();
        } else {
            if (argc > 2) throw std::invalid_argument("Usage: Euler1020 [N | --self-test]");
            u64 limit = TARGET;
            if (argc == 2) {
                const std::string argument(argv[1]);
                const auto parsed = std::from_chars(argument.data(), argument.data() + argument.size(), limit);
                if (parsed.ec != std::errc{} || parsed.ptr != argument.data() + argument.size() || limit > MAX_LIMIT) {
                    throw std::invalid_argument("N must be an integer from 0 to 18446744073709551614");
                }
            }
            std::cout << modified_sum<Modular>(limit) << '\n';
        }
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Python

#!/usr/bin/env python3
"""Project Euler Problem 1020 - Modified Sum of Fibonacci Numbers."""

import sys

MOD = 1_000_000_007
TARGET = 10**18
MAX_LIMIT = (1 << 64) - 2


def require(condition, description):
    if not condition:
        raise RuntimeError("Check failed: " + description)


class Modular:
    @staticmethod
    def add(a, b):
        total = a + b
        return total - MOD if total >= MOD else total

    @staticmethod
    def multiply(a, b):
        return a * b % MOD


# Python integers are unbounded, so the exact ring needs no overflow check.
class Exact:
    @staticmethod
    def add(a, b):
        return a + b

    @staticmethod
    def multiply(a, b):
        return a * b


# A 2x2 matrix is a pair of rows ((a, b), (c, d)).
ZERO = ((0, 0), (0, 0))
IDENTITY = ((1, 0), (0, 1))
FIBONACCI = ((1, 1), (1, 0))


def matrix_add(ring, x, y):
    return tuple(tuple(ring.add(x[i][j], y[i][j]) for j in range(2)) for i in range(2))


def matrix_multiply(ring, x, y):
    return tuple(tuple(ring.add(ring.multiply(x[i][0], y[0][j]), ring.multiply(x[i][1], y[1][j]))
                       for j in range(2)) for i in range(2))


def matrix_power(ring, base, exponent):
    result = IDENTITY
    while exponent != 0:
        if exponent & 1:
            result = matrix_multiply(ring, result, base)
        exponent >>= 1
        if exponent != 0:
            base = matrix_multiply(ring, base, base)
    return result


def modified_sum(ring, limit):
    require(limit <= MAX_LIMIT, "N + 1 fits in 64 bits")
    count = limit + 1
    bits = count.bit_length()
    factor, block = [], [IDENTITY]
    square = FIBONACCI
    for i in range(bits):
        shifted = matrix_multiply(ring, square, FIBONACCI)
        block.append(matrix_multiply(ring, block[-1], matrix_add(ring, IDENTITY, shifted)))
        factor.append(shifted)
        if i + 1 < bits:
            square = matrix_multiply(ring, square, square)
    total, prefix = ZERO, IDENTITY
    for bit in reversed(range(bits)):
        if (count >> bit) & 1:
            total = matrix_add(ring, total, matrix_multiply(ring, prefix, block[bit]))
            prefix = matrix_multiply(ring, prefix, factor[bit])
    return total[0][1]


# A pair (a, b) stands for a + b * sqrt(5) modulo MOD.
def quadratic_add(x, y):
    return (Modular.add(x[0], y[0]), Modular.add(x[1], y[1]))


def quadratic_multiply(x, y):
    return ((x[0] * y[0] + 5 * (x[1] * y[1])) % MOD, (x[0] * y[1] + x[1] * y[0]) % MOD)


def quadratic_power(base, exponent):
    result = (1, 0)
    while exponent != 0:
        if exponent & 1:
            result = quadratic_multiply(result, base)
        exponent >>= 1
        if exponent != 0:
            base = quadratic_multiply(base, base)
    return result


def weighted_sum(limit, base, phi):
    if limit == 0:
        return (1, 0)
    if limit & 1:
        return quadratic_multiply(quadratic_add((1, 0), quadratic_multiply(base, phi)),
                                  weighted_sum(limit // 2, quadratic_multiply(base, base), phi))
    return quadratic_add(weighted_sum(limit - 1, base, phi),
                         quadratic_multiply(quadratic_power(base, limit), quadratic_power(phi, limit.bit_count())))


def binet_sum(limit):
    half = (MOD + 1) // 2
    phi = (half, half)
    total = weighted_sum(limit, phi, phi)
    return Modular.add(total[1], total[1])


def brute_force_prefixes(ring, limit):
    fibonacci = [0] * (limit + 65)
    fibonacci[1] = 1
    for i in range(2, len(fibonacci)):
        fibonacci[i] = ring.add(fibonacci[i - 1], fibonacci[i - 2])
    prefixes, total = [], 0
    for k in range(limit + 1):
        total = ring.add(total, fibonacci[k + k.bit_count()])
        prefixes.append(total)
    return prefixes


def run_tests():
    require(modified_sum(Exact, 10) == 369, "given S(10), matrix product")
    require(modified_sum(Modular, 10) == 369, "given S(10) modulo the prime")
    require(binet_sum(10) == 369, "given S(10), Binet method")
    s50 = 161_052_232_733
    require(modified_sum(Exact, 50) == s50, "given S(50), matrix product")
    require(modified_sum(Modular, 50) == s50 % MOD, "given S(50) modulo the prime")
    require(binet_sum(50) == s50 % MOD, "given S(50), Binet method")

    exact = brute_force_prefixes(Exact, 100)
    require(exact[10] == 369 and exact[50] == s50, "given values by direct summation")
    for limit in range(101):
        require(modified_sum(Exact, limit) == exact[limit], "exact sums for every N up to 100")
    prefixes = brute_force_prefixes(Modular, 1_000_000)
    for limit in range(4097):
        require(modified_sum(Modular, limit) == prefixes[limit], "matrix product for every N up to 4096")
        require(binet_sum(limit) == prefixes[limit], "Binet method for every N up to 4096")
    for limit in (0, 1, 2, 7, 8, 15, 16, 31, 32, 1000, 123_456, 1_000_000):
        require(modified_sum(Modular, limit) == prefixes[limit], "matrix product against direct summation")
        require(binet_sum(limit) == prefixes[limit], "Binet method against direct summation")

    answer = modified_sum(Modular, TARGET)
    require(answer == binet_sum(TARGET), "both methods at N = 10^18")
    step = Modular.add(answer, MOD - modified_sum(Modular, TARGET - 1))
    last = matrix_power(Modular, FIBONACCI, TARGET + TARGET.bit_count())[0][1]
    require(step == last, "S(N) - S(N - 1) = F(N + s(N)) at N = 10^18")
    require(modified_sum(Modular, MAX_LIMIT) == binet_sum(MAX_LIMIT), "both methods at the largest N")
    print("All checks passed: S(10) and S(50), exact sums for N up to 100, direct sums for every N up to 4096 "
          "and at 12 values up to 1000000, the Binet method, the last term at N = 10^18 and both methods at the "
          "largest N.")


# Like std::from_chars into an unsigned 64-bit value: decimal digits only, no sign or spaces.
def parse_limit(text):
    digits = text.lstrip("0") or "0"
    if (not text or any(c not in "0123456789" for c in text)
            or len(digits) > len(str(MAX_LIMIT)) or int(digits) > MAX_LIMIT):
        raise ValueError("N must be an integer from 0 to 18446744073709551614")
    return int(digits)


def main(argv):
    try:
        if len(argv) == 2 and argv[1] == "--self-test":
            run_tests()
        else:
            if len(argv) > 2:
                raise ValueError("Usage: Euler1020.py [N | --self-test]")
            limit = parse_limit(argv[1]) if len(argv) == 2 else TARGET
            print(modified_sum(Modular, limit))
    except (ValueError, RuntimeError) as error:
        print(error, file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))

Java

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class Euler1020 {
    // N is an unsigned 64-bit value stored in a long, as in the C++ program; MAX_LIMIT is 2^64 - 2.
    private static final long MOD = 1_000_000_007L;
    private static final long TARGET = 1_000_000_000_000_000_000L;
    private static final long MAX_LIMIT = -2L;

    private static void require(boolean condition, String description) {
        if (!condition) throw new IllegalStateException("Check failed: " + description);
    }

    interface Ring<T> {
        T zero();
        T one();
        T add(T a, T b);
        T multiply(T a, T b);
    }

    static final Ring<Long> MODULAR = new Ring<>() {
        public Long zero() { return 0L; }
        public Long one() { return 1L; }

        public Long add(Long a, Long b) {
            long sum = a + b;
            return sum >= MOD ? sum - MOD : sum;
        }

        public Long multiply(Long a, Long b) { return a * b % MOD; }
    };

    // BigInteger is unbounded, so the exact ring needs no overflow check.
    static final Ring<BigInteger> EXACT = new Ring<>() {
        public BigInteger zero() { return BigInteger.ZERO; }
        public BigInteger one() { return BigInteger.ONE; }
        public BigInteger add(BigInteger a, BigInteger b) { return a.add(b); }
        public BigInteger multiply(BigInteger a, BigInteger b) { return a.multiply(b); }
    };

    static final class Matrix<T> {
        final T a00, a01, a10, a11;

        Matrix(T a00, T a01, T a10, T a11) {
            this.a00 = a00;
            this.a01 = a01;
            this.a10 = a10;
            this.a11 = a11;
        }

        static <T> Matrix<T> zero(Ring<T> ring) {
            return new Matrix<>(ring.zero(), ring.zero(), ring.zero(), ring.zero());
        }

        static <T> Matrix<T> identity(Ring<T> ring) {
            return new Matrix<>(ring.one(), ring.zero(), ring.zero(), ring.one());
        }

        static <T> Matrix<T> fibonacci(Ring<T> ring) {
            return new Matrix<>(ring.one(), ring.one(), ring.one(), ring.zero());
        }

        Matrix<T> plus(Ring<T> ring, Matrix<T> other) {
            return new Matrix<>(ring.add(a00, other.a00), ring.add(a01, other.a01),
                    ring.add(a10, other.a10), ring.add(a11, other.a11));
        }

        Matrix<T> times(Ring<T> ring, Matrix<T> other) {
            return new Matrix<>(
                    ring.add(ring.multiply(a00, other.a00), ring.multiply(a01, other.a10)),
                    ring.add(ring.multiply(a00, other.a01), ring.multiply(a01, other.a11)),
                    ring.add(ring.multiply(a10, other.a00), ring.multiply(a11, other.a10)),
                    ring.add(ring.multiply(a10, other.a01), ring.multiply(a11, other.a11)));
        }
    }

    static <T> Matrix<T> power(Ring<T> ring, Matrix<T> base, long exponent) {
        Matrix<T> result = Matrix.identity(ring);
        while (exponent != 0) {
            if ((exponent & 1) != 0) result = result.times(ring, base);
            exponent >>>= 1;
            if (exponent != 0) base = base.times(ring, base);
        }
        return result;
    }

    static <T> T modifiedSum(Ring<T> ring, long limit) {
        require(Long.compareUnsigned(limit, MAX_LIMIT) <= 0, "N + 1 fits in 64 bits");
        long count = limit + 1;
        int bits = 64 - Long.numberOfLeadingZeros(count);
        List<Matrix<T>> factor = new ArrayList<>();
        List<Matrix<T>> block = new ArrayList<>();
        block.add(Matrix.identity(ring));
        Matrix<T> square = Matrix.fibonacci(ring);
        for (int i = 0; i < bits; ++i) {
            Matrix<T> shifted = square.times(ring, Matrix.fibonacci(ring));
            block.add(block.get(block.size() - 1).times(ring, Matrix.identity(ring).plus(ring, shifted)));
            factor.add(shifted);
            if (i + 1 < bits) square = square.times(ring, square);
        }
        Matrix<T> total = Matrix.zero(ring);
        Matrix<T> prefix = Matrix.identity(ring);
        for (int bit = bits - 1; bit >= 0; --bit) {
            if (((count >>> bit) & 1) != 0) {
                total = total.plus(ring, prefix.times(ring, block.get(bit)));
                prefix = prefix.times(ring, factor.get(bit));
            }
        }
        return total.a01;
    }

    // a + b * sqrt(5) modulo MOD
    static final class Quadratic {
        final long a, b;

        Quadratic(long a, long b) {
            this.a = a;
            this.b = b;
        }

        Quadratic plus(Quadratic other) {
            return new Quadratic(MODULAR.add(a, other.a), MODULAR.add(b, other.b));
        }

        Quadratic times(Quadratic other) {
            return new Quadratic((a * other.a % MOD + 5 * (b * other.b % MOD)) % MOD,
                    (a * other.b % MOD + b * other.a % MOD) % MOD);
        }
    }

    static Quadratic power(Quadratic base, long exponent) {
        Quadratic result = new Quadratic(1, 0);
        while (exponent != 0) {
            if ((exponent & 1) != 0) result = result.times(base);
            exponent >>>= 1;
            if (exponent != 0) base = base.times(base);
        }
        return result;
    }

    static Quadratic weightedSum(long limit, Quadratic base, Quadratic phi) {
        if (limit == 0) return new Quadratic(1, 0);
        if ((limit & 1) != 0) {
            return new Quadratic(1, 0).plus(base.times(phi)).times(weightedSum(limit >>> 1, base.times(base), phi));
        }
        return weightedSum(limit - 1, base, phi).plus(power(base, limit).times(power(phi, Long.bitCount(limit))));
    }

    static long binetSum(long limit) {
        long half = (MOD + 1) / 2;
        Quadratic phi = new Quadratic(half, half);
        Quadratic total = weightedSum(limit, phi, phi);
        return MODULAR.add(total.b, total.b);
    }

    static <T> List<T> bruteForcePrefixes(Ring<T> ring, int limit) {
        List<T> fibonacci = new ArrayList<>();
        fibonacci.add(ring.zero());
        fibonacci.add(ring.one());
        for (int i = 2; i < limit + 65; ++i) fibonacci.add(ring.add(fibonacci.get(i - 1), fibonacci.get(i - 2)));
        List<T> prefixes = new ArrayList<>();
        T total = ring.zero();
        for (int k = 0; k <= limit; ++k) {
            total = ring.add(total, fibonacci.get(k + Integer.bitCount(k)));
            prefixes.add(total);
        }
        return prefixes;
    }

    static void runTests() {
        require(modifiedSum(EXACT, 10).equals(BigInteger.valueOf(369)), "given S(10), matrix product");
        require(modifiedSum(MODULAR, 10) == 369, "given S(10) modulo the prime");
        require(binetSum(10) == 369, "given S(10), Binet method");
        BigInteger s50 = BigInteger.valueOf(161_052_232_733L);
        long s50Mod = s50.mod(BigInteger.valueOf(MOD)).longValue();
        require(modifiedSum(EXACT, 50).equals(s50), "given S(50), matrix product");
        require(modifiedSum(MODULAR, 50) == s50Mod, "given S(50) modulo the prime");
        require(binetSum(50) == s50Mod, "given S(50), Binet method");

        List<BigInteger> exact = bruteForcePrefixes(EXACT, 100);
        require(exact.get(10).equals(BigInteger.valueOf(369)) && exact.get(50).equals(s50),
                "given values by direct summation");
        for (int limit = 0; limit <= 100; ++limit) {
            require(modifiedSum(EXACT, limit).equals(exact.get(limit)), "exact sums for every N up to 100");
        }
        List<Long> prefixes = bruteForcePrefixes(MODULAR, 1_000_000);
        for (int limit = 0; limit <= 4096; ++limit) {
            long expected = prefixes.get(limit);
            require(modifiedSum(MODULAR, limit) == expected, "matrix product for every N up to 4096");
            require(binetSum(limit) == expected, "Binet method for every N up to 4096");
        }
        for (int limit : new int[] {0, 1, 2, 7, 8, 15, 16, 31, 32, 1000, 123_456, 1_000_000}) {
            long expected = prefixes.get(limit);
            require(modifiedSum(MODULAR, limit) == expected, "matrix product against direct summation");
            require(binetSum(limit) == expected, "Binet method against direct summation");
        }

        long answer = modifiedSum(MODULAR, TARGET);
        require(answer == binetSum(TARGET), "both methods at N = 10^18");
        long step = MODULAR.add(answer, MOD - modifiedSum(MODULAR, TARGET - 1));
        long last = power(MODULAR, Matrix.fibonacci(MODULAR), TARGET + Long.bitCount(TARGET)).a01;
        require(step == last, "S(N) - S(N - 1) = F(N + s(N)) at N = 10^18");
        require(modifiedSum(MODULAR, MAX_LIMIT) == binetSum(MAX_LIMIT), "both methods at the largest N");
        System.out.println("All checks passed: S(10) and S(50), exact sums for N up to 100, direct sums for every N "
                + "up to 4096 and at 12 values up to 1000000, the Binet method, the last term at N = 10^18 and both "
                + "methods at the largest N.");
    }

    static long parseLimit(String text) {
        boolean digits = !text.isEmpty();
        for (int i = 0; i < text.length() && digits; ++i) {
            char digit = text.charAt(i);
            digits = digit >= '0' && digit <= '9';
        }
        try {
            if (digits) {
                long limit = Long.parseUnsignedLong(text);
                if (Long.compareUnsigned(limit, MAX_LIMIT) <= 0) return limit;
            }
        } catch (NumberFormatException tooLarge) {
            // more than 2^64 - 1: reported with the same message as a malformed N
        }
        throw new IllegalArgumentException("N must be an integer from 0 to 18446744073709551614");
    }

    public static void main(String[] args) {
        try {
            if (args.length == 1 && args[0].equals("--self-test")) {
                runTests();
            } else {
                if (args.length > 1) throw new IllegalArgumentException("Usage: java Euler1020 [N | --self-test]");
                long limit = args.length == 1 ? parseLimit(args[0]) : TARGET;
                System.out.println(modifiedSum(MODULAR, limit));
            }
        } catch (RuntimeException error) {
            System.err.println(error.getMessage());
            System.exit(1);
        }
    }
}