Problem Description
Given an integer n, we need to determine the total number of good digit strings of length n such that digits at even indices are even (0, 2, 4, 6, 8) and digits at odd indices are prime (2, 3, 5, or 7). A digit string is a string consisting of digits 0 through 9 (with possible leading zeros). The answer should be returned modulo 10^9 + 7.
Key Insights
- The string has n positions, where positions are 0-indexed.
- Even indices must contain one of 5 even digits {0, 2, 4, 6, 8}.
- Odd indices must contain one of 4 prime digits {2, 3, 5, 7}.
- Count the number of even index positions as ceil(n / 2) and odd index positions as floor(n / 2).
- The total good numbers equals 5^(ceil(n / 2)) * 4^(floor(n / 2)) modulo 10^9 + 7.
- Use fast modular exponentiation due to the large constraint on n (up to 10^15).
Space and Time Complexity
Time Complexity: O(log n) due to fast modular exponentiation. Space Complexity: O(1) as only a fixed amount of memory is used.
Solution
We determine the count of good digit strings by dividing the positions into even and odd index positions. Even indexes must be one of the 5 even digits, so they contribute 5 possibilities each; odd indexes must be one of the 4 prime digits, and they contribute 4 possibilities each. If n is the length, then:
- Number of even indexed positions = ceil(n / 2)
- Number of odd indexed positions = floor(n / 2)
Thus, the total number of good strings is: 5^(ceil(n / 2)) * 4^(floor(n / 2)) modulo (10^9 + 7).
To compute these large exponents efficiently, we use fast modular exponentiation (also known as modular power). This ensures that even for n as large as 10^15, the exponents are calculated quickly.
The provided code solutions in Python, JavaScript, C++, and Java include detailed inline comments to clarify each step.