Count Good Numbers - Problem

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 (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is 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.

Input & Output

Example 1 — Small Case
$ Input: n = 1
Output: 5
💡 Note: Single digit at even position 0. Valid digits: 0,2,4,6,8. Total = 5.
Example 2 — Two Positions
$ Input: n = 2
Output: 20
💡 Note: Position 0 (even): 5 choices, Position 1 (odd): 4 choices. Total = 5 × 4 = 20.
Example 3 — Larger Input
$ Input: n = 50
Output: 564908303
💡 Note: Even positions: 25, Odd positions: 25. Result = 5²⁵ × 4²⁵ mod (10⁹ + 7).

Constraints

  • 1 ≤ n ≤ 1015

Visualization

Tap to expand
Count Good Numbers INPUT Given: n = 1 (length of digit string) Digit Positions pos 0 EVEN pos 1 ODD pos 2 EVEN pos 3 ODD Rules Even positions: 0,2,4,6,8 (5 choices) Odd positions: 2,3,5,7 (4 choices - primes) ALGORITHM STEPS 1 Count Positions evenPos = (n+1)/2 oddPos = n/2 2 For n=1 evenPos = (1+1)/2 = 1 oddPos = 1/2 = 0 3 Apply Formula result = 5^evenPos * 4^oddPos result = 5^1 * 4^0 4 Use Fast Power Modular exponentiation mod = 10^9 + 7 Formula ans = (5^evenPos * 4^oddPos) % (10^9 + 7) FINAL RESULT For n = 1: evenPos = 1 oddPos = 0 5^1 * 4^0 = 5 * 1 = 5 Valid Digits (pos 0) 0 2 4 6 8 OUTPUT 5 Key Insight: The problem uses counting principle: multiply choices at each position. Even indices have 5 choices (0,2,4,6,8), odd indices have 4 choices (2,3,5,7 - primes). Use fast modular exponentiation for large n to compute 5^evenPos * 4^oddPos efficiently. TutorialsPoint - Count Good Numbers | Optimal Solution (Fast Exponentiation)
Asked in
Google 25 Amazon 18 Microsoft 15
32.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen