AlgoInsight

DSA problem

Count Good Numbers

MediumMaths / GeometryPattern: Maths / Geometrytop600AmazonGoogleMicrosoftAdobeBloomberg

A digit string of length n is called good when:

Given an integer n, return the count of digit strings of length n that are good. Because the answer can be astronomically large, return it modulo 10^9 + 7.

The structure is purely combinatorial. There are ceil(n / 2) even-indexed slots and floor(n / 2) odd-indexed slots. Each even-indexed slot has 5 valid digits (the evens) and each odd-indexed slot has 4 valid digits (the primes 2, 3, 5, 7). Since the choices at different positions are independent, the total count is 5^ceil(n/2) * 4^floor(n/2) modulo 10^9 + 7.

Because n can be as large as 10^15, we cannot iterate n times. Use modular fast exponentiation (binary exponentiation) to compute each power in O(log n) time. Be careful with overflow: in languages without arbitrary-precision integers (Java, C++, JavaScript with care), do intermediate multiplications in 64-bit (long / long long / BigInt) before applying the modulus.

Examples

Example 1
Input: n = 1
Output: 5
Explanation: A string of length 1 has only one even-indexed slot, so there are 5 choices: 0, 2, 4, 6, 8.
Example 2
Input: n = 4
Output: 400
Explanation: There are 2 even-indexed slots (5 choices each = 25) and 2 odd-indexed slots (4 choices each = 16). Total = 25 * 16 = 400.
Example 3
Input: n = 50
Output: 564908303
Explanation: For very large counts, the answer must be returned modulo 10^9 + 7.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

mathrecursion

Browse all DSA problems