Problem
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2
, 3
, 5
, or 7
).
- For example,
"2582"
is good because the digits (2
and8
) at even positions are even and the digits (5
and2
) at odd positions are prime. However,"3245"
is not good because3
is at an even index but is not even.
Given an integer n
, return the total number of good digit strings of length n
. Since the answer may be large, return it modulo 109 + 7
.
A digit string is a string consisting of digits 0
through 9
that may contain leading zeros.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= n <= 10^15
Solution
The problem involves finding the total count of “good” digit strings of length n
where a digit string is considered “good” if it satisfies:
- Digits at even indices (0, 2, …) are even (
0, 2, 4, 6, 8
). - Digits at odd indices (1, 3, …) are prime (
2, 3, 5, 7
).
The constraints allow us to compute the count efficiently using dynamic programming or mathematical calculations.
Method 1 - Using DP
So,
- A digit at an even index has 5 possible choices:
0, 2, 4, 6, 8
. - A digit at an odd index has 4 possible choices:
2, 3, 5, 7
.
The total number of “good” digit strings can be determined by:
- Using the combination
5^(ceil(n / 2))
for digits at even positions. - Using the combination
4^(floor(n / 2))
for digits at odd positions.
Combining these, the formula is:
|
|
where:
count_even_indices = ceil(n / 2)
— the number of even positions.count_odd_indices = floor(n / 2)
— the number of odd positions.MOD = 10^9 + 7
is used to prevent overflow.
Steps
- Compute the number of even and odd indices based on
n
. - Efficiently calculate modular exponentiation for
5^(count_even_indices)
and4^(count_odd_indices)
. - Multiply the results and return modulo
10^9 + 7
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- Calculating modular exponentiation (
pow(base, exp, MOD)
in Python orMath.pow
in Java) takesO(log(exp))
. - Thus, the total time complexity is
O(log(n))
becauseexp
depends onn
.
- Calculating modular exponentiation (
- 🧺 Space complexity:
O(1)