PROBLEM LINK:
DIFFICULTY
SIMPLE
PREREQUISITES
Simple Math, Repeated Squaring
PROBLEM
How many sequences of 0s and 1s (0 meaning a hug, 1 meaning a kiss) of length N are possible, such that after the first 1 appears at index i, every alternate index after i - formally, i+2, i+4, i+6 and so on - is also 1. Note that this constraint is forced only by the first 1 and no subsequent 1s.
QUICK EXPLANATION
Suppose the sequence was to start with a 0, then all possible sequences of length N-1 are valid.
Now, if the sequence were to start with a 1, then every odd index in the sequence (assuming the sequence is 1-based) will be 1; the rest of the floor(N/2) indices can be either 0 or 1, mutually exclusively.
Thus we get the formula
f(N) = f(N-1) + 2
floor(N/2)
Since N can be as much as 109 we cannot use this recursive formulation as it is.
The Explanation section below is about finding a closed form from the above recursive formula
EXPLANATION
Seeing the floor function and division by 2 immediately gives us the insight that we should find the formula for odd and even N.
Let f
o
(N)
and f
e
(N)
be the functions that are defined for the odd and even values of N respectively. Thus,
f(N) = if N is odd then f
o
(N) else f
e
(N)
(1) ... f
o
(N) = f
e
(N-1) + 2
(N-1)/2
(2) ... f
e
(N) = f
o
(N-1) + 2
N/2
From (1)
and (2)
we can derive
(3) ... f
o
(N) = f
o
(N-2) + 2
(N-1)/2
+ 2
(N-1)/2
(4) ... f
e
(N) = f
e
(N-2) + 2
N/2
+ 2
(N-2)/2
Where,
f
o
(1) = 2
f
e
(0) = 1
These formulas are already very usable. We can use matrix exponentiation on f
o
(N)
or f
e
(N)
based on whether N is even or odd. But we can do a little better and find closed form formulas of f
o
and f
e
.
Let,
t
o
(N)
= f
o
(N) - f
o
(N-2)
= 2
(N-1)/2
+ 2
(N-1)/2
= 2
(N+1)/2
t
o
(3) = 2
2
t
o
(5) = 2
3
t
o
(7) = 2
4
...
t
o
(N) = 2
(N+1)/2
Adding all of the above gives us,
f
o
(N) - f
o
(1) =
∑[n = 0 to (N+1)/2]
2
n
- 2
1
- 2
0
f
o
(N) - 2 = 2
(N+1)/2 + 1
- 1 - 2 - 1
(summation of Geometric Progression)
f
o
(N) = 2
(N+1)/2 + 1
- 2
Similarly, we want to find the closed form for f
e
.
Let,
t
e
(N)
= f
e
(N) - f
e
(N-2)
= 2
N/2
+ 2
N/2 - 1
t
e
(2) = 2
1
+ 2
0
t
e
(4) = 2
2
+ 2
1
t
e
(6) = 2
3
+ 2
2
...
t
e
(N) = 2
N/2
+ 2
N/2 - 1
Adding all of the above gives us,
f
e
(N) - f
e
(0) =
∑[n = 0 to N/2]
2
n
- 2
0
+ ∑[n = 0 to (N/2 - 1)]
2
n
f
e
(N) - 1 = 2
N/2 + 1
- 1 - 1 + 2
N/2
- 1
(summation of Geometric Progression)
f
e
(N) = 2
N/2 + 1
+ 2
N/2
- 2
Thus we can find the value of f(N)
from the following two expressions
f(N) = 2
(N+1)/2 + 1
- 2
, for odd N
f(N) = 2
N/2 + 1
+ 2
N/2
- 2
, for even N
To further simplify the formula, you can rewrite the expressions for odd and even N as follows,
f(N) = 2
(N+1)/2
+ 2
(N+1)/2
- 2
, for odd N
f(N) = 2
N/2 + 1
+ 2
N/2
- 2
, for even N
Or,
f(N) = 2
ceil((N+1)/2)
+ 2
floor((N+1)/2)
- 2
, for any N
The value of 2
n
can be found by repeated squaring.
SETTERS SOLUTION
Can be found here
TESTERS SOLUTION
Can be found here