What it teaches: Fast modular exponentiation for counts with huge n.
Practise it on judges as “Count Good Numbers”.
In plain words
Build a digit string slot by slot. Even slots (0, 2, 4, …) can hold 5 choices (0, 2, 4, 6, 8); odd slots can hold 4 choices (2, 3, 5, 7). Multiply the choices: 5 to the power of the even slots times 4 to the power of the odd slots. n can be huge, so compute powers by repeated squaring.
Return the count modulo 10⁹ + 7. Example: n = 4 → 400.
The problem
A digit string is good if digits at even indices are even (0, 2, 4, 6, 8) and digits at odd indices are prime (2, 3, 5, 7). Return the number of good strings of length n, modulo 10⁹ + 7.
Example 1
Input: n = 4
Output: 400
Constraints
1 ≤ n ≤ 10¹⁵
Pattern clues in the wording
→ Independent choices per position
→ n up to 10¹⁵
→ Answer modulo 10⁹ + 7
These clues point to Number Theory and Combinatorics: GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.
Stuck? Take one hint at a time
Solution · starter
class Solution {
public int countGoodNumbers(long n) {
return 0;
}
}
Write your solution locally or in your editor for now. Pick Java, Python, C++, JavaScript or Go above: every solution on this page switches with it. The in-browser runner will run these tests right here.
Step 1/4Slots 0 and 2 have 5 choices each; slots 1 and 3 have 4 each.
Approach 1
class Solution {
private static final long P = 1_000_000_007L;
public int countGoodNumbers(long n) {
return (int) (power(5, (n + 1) / 2) * power(4, n / 2) % P);
}
private long power(long b, long e) {
long r = 1;
b %= P;
while (e > 0) {
if ((e & 1) == 1) r = r * b % P;
b = b * b % P;
e >>= 1;
}
return r;
}
}