Example 1
- Input
- n = 1
- Output
- 5
The five good strings are 0, 2, 4, 6 and 8. There are zero complete pairs and one extra even position.
Count length-n decimal strings with even digits at even indices and prime digits at odd indices. Leading zero is allowed; return the count modulo 1,000,000,007.
A good digit string has one of 0,2,4,6,8 at each even index and one of 2,3,5,7 at each odd index, using zero-based indices. Given n, return the number of good strings of length n, modulo 10^9 + 7. Leading zeros are allowed, so the first position has five choices just like every other even position.
For example, 2582 is good and 3245 is not. The official problem permits n up to 10^15, making a loop through every position impractical.
1 <= n <= 10^15.10^9 + 7; strings may begin with zero.The five good strings are 0, 2, 4, 6 and 8. There are zero complete pairs and one extra even position.
Two complete pairs give 20 × 20 = 400, equivalently 5 × 4 × 5 × 4.
There are 25 complete pairs. Reducing 20^25 modulo 1,000,000,007 gives 564908303.
One complete pair gives twenty choices and the final even position gives five more: 20 × 5 = 100.
Independent positions multiply their choices: there are five choices at each of the ceil(n/2) even indices and four at each of the floor(n/2) odd indices. Thus the answer is 5^ceil(n/2) × 4^floor(n/2) modulo the required modulus. In Example 1, the single even position allows 0, 2, 4, 6 or 8. Pairing one even and one odd position gives twenty possibilities; count complete pairs with fast exponentiation and multiply by five if one even position remains. Residues stay small after reduction, but multiplying two residues can still approach 10^18, so JavaScript needs exact integer multiplication.
Reveal Modular Power: intuition, complexity, and code
20^floor(n/2) modulo the modulus by squaring and halving; multiply by five when n is odd.n = 10^15, iteration by position is infeasible, but exponentiation still takes fewer than fifty iterations.base * base and applying % afterward cannot restore digits already lost to rounding.exponent >> 1 truncates the exponent to 32 bits; BigInt division handles the full input bound.Independent choices produce powers. Binary exponentiation evaluates huge exponents with few operations, while modular reduction controls operand sizes only if each multiplication is exact in the chosen runtime.