Count Good Numbers - Problem
Count Good Numbers is a fascinating combinatorics problem that challenges you to count valid digit strings with specific constraints.
A digit string is considered "good" if it follows these rules:
• Digits at even positions (0, 2, 4, ...) must be even (0, 2, 4, 6, 8)
• Digits at odd positions (1, 3, 5, ...) must be prime (2, 3, 5, 7)
For example:
•
•
Given an integer
A digit string is considered "good" if it follows these rules:
• Digits at even positions (0, 2, 4, ...) must be even (0, 2, 4, 6, 8)
• Digits at odd positions (1, 3, 5, ...) must be prime (2, 3, 5, 7)
For example:
•
"2582" is good: positions 0,2 have even digits (2,8), positions 1,3 have prime digits (5,2)•
"3245" is not good: position 0 has odd digit (3)Given an integer
n, return the total count of good digit strings of length n. Since the answer can be very large, return it modulo 109 + 7. Input & Output
example_1.py — Basic Case
$
Input:
n = 1
›
Output:
5
💡 Note:
For length 1, only position 0 exists (even position). Valid digits are 0,2,4,6,8 - total of 5 good numbers.
example_2.py — Small Even Length
$
Input:
n = 4
›
Output:
400
💡 Note:
Positions 0,2 are even (5 choices each), positions 1,3 are odd (4 choices each). Total = 5² × 4² = 25 × 16 = 400.
example_3.py — Small Odd Length
$
Input:
n = 50
›
Output:
564908303
💡 Note:
25 even positions and 25 odd positions. Result is (5²⁵ × 4²⁵) mod (10⁹ + 7) = 564908303.
Constraints
- 1 ≤ n ≤ 1015
- The answer must be returned modulo 109 + 7
- Large input size requires efficient O(log n) solution
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Position Rules
Even positions (0,2,4...) need even digits (0,2,4,6,8), odd positions (1,3,5...) need prime digits (2,3,5,7)
2
Count Position Types
For length n: even positions = ceil(n/2), odd positions = floor(n/2)
3
Apply Multiplication Principle
Total combinations = 5^(even_positions) × 4^(odd_positions)
4
Use Fast Exponentiation
Compute large powers efficiently using binary exponentiation in O(log n) time
Key Takeaway
🎯 Key Insight: Independence of positions allows us to use the multiplication principle. Fast exponentiation makes it efficient for very large n values up to 10^15.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code