#1922

Count Good Numbers

Medium Modular exponentiation

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A digit string is "good" if digits at even indexes are even (0,2,4,6,8) and digits at odd indexes are prime (2,3,5,7). Count good strings of length n, modulo 1e9+7. n can be up to 10^15.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: even positions can hold 5 digits, odd positions 4 digits. How many strings of length n (up to 10^15)?

Why this works: choices multiply: 5^(even count) × 4^(odd count). Fast power with modulo handles the huge exponent.

Example: n = 4

positions 0,1,2,3 → 2 even, 2 odd5² × 4² = 25 × 16 = 400

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Taking the modulus only at the end. Every multiplication must be reduced, or a long overflows.