Count Good Numbers Problem
Description
LeetCode Problem 1922.
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 (2and8) at even positions are even and the digits (5and2) at odd positions are prime. However,"3245"is not good because3is 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 10^9 + 7.
A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Example 1:
Input: n = 1
Output: 5
Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8".
Example 2:
Input: n = 4
Output: 400
Example 3:
Input: n = 50
Output: 564908303
Constraints:
1 <= n <= 10^15
Solution
Approach: Fast Exponentiation
In a good number, digits at even indices must be even (5 choices: 0, 2, 4, 6, 8) and digits at odd indices must be prime (4 choices: 2, 3, 5, 7). A string of length n has ceil(n / 2) even positions and floor(n / 2) odd positions, so the count is
5ceil(n/2) * 4floor(n/2) (mod 109 + 7).
Since n can be 1015, compute the powers with fast exponentiation (repeated squaring), reducing modulo 109 + 7 after each multiplication.
Complexity: O(log n) time and O(1) space.
class Solution:
def countGoodNumbers(self, n: int) -> int:
mod = 10**9 + 7
return pow(5, (n + 1) >> 1, mod) * pow(4, n >> 1, mod) % mod