WARNING: The text below provides a guidance for a Project Euler problem.

  • If you pride yourself in tackling problems entirely on your own, you are encouraged to exit this post right now.

  • If you are simply looking for a hint for the problem, please visit the »Project Euler’s official forum«. You may find some hints here, but if you don’t want your problem spoiled, scroll cautiously.

  • If you are looking for a readily available copy/paste answer, you will not find it here. All of the code snippets in the post have been stripped of some crucial lines (these are clearly marked). It is my aim that anyone able to replicate the answer based on such snippets will have to understand the solution conceptually. At that point, by virtue of learning something new, I believe he deserves it anyway.

  • Guidance for future problems will not be published before 100 people have solved the problem and there are at least two more recent problems.




















Two heads are better than one

Let be the random variable counting the number of times we toss an unbiased coin until we obtain two consecutive heads. Let denote the probability . The problem revolves about computing for large values precisely.

As a helper variable, define to denote the probability that after tosses, we obtain precisely a sequence of the form , where in the part (the first tosses) no two consecutive heads appear. Define also to be the number of sequences of tosses of length , such that no two consecutive heads appear. We have a clear relationship between and (because the last three tosses in the sequence where we have encountered a pair of heads for the first time must be precisely ). We can express in terms of as

and thus we turn into reasoning about first. We can obtain a recursive relationship by discerning two cases for the last coin toss in the sequence ( comes from the case where the last toss is , from the case where the last toss is , as then the second to last toss must have necessarily been ). Noticing furthermore that the first values of are , which are precisely the second and third terms of the Fibonacci sequence, the recursive relationship actually tells us that is the Fibonacci sequence and

The trick for being able to calculate this efficiently is to turn the expression into a geometric series! For this we may use the fact that the Fibonacci numbers can be obtained by matrix exponentiation. In particular, the -th Fibonacci number is the entry of the matrix where

.

We may hence rewrite:

The determinant of is smaller than one, hence the geometric series converges to:

Finally, we obtain:

At last, calculating is nothing else than working out using modular arithmetic. The following succinct piece of Julia code gives answer in mere seconds.

using Nemo
R = ResidueRing(ZZ, 10^9+9)
F = matrix(R, [1 1; 1 0])
Q(n) = (F^# <REMOVED>
@time Q(10^18)