Skip to main content
Back to problems
#1922
Medium Algorithms

Count good numbers

Math Recursion
57.4% acceptance
Feb 25, 2026
2405
594
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 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn count_good_numbers(n: i64) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let even_count = (n + 1) / 2; // positions at even indices
    let odd_count = n / 2; // positions at odd indices
    // 5 choices for even positions (0,2,4,6,8), 4 for odd (2,3,5,7)
    let result = Self::power(5, even_count, MOD) * Self::power(4, odd_count, MOD) % MOD;
    result as i32
  }

  fn power(mut base: i64, mut exp: i64, modulus: i64) -> i64 {
    let mut result = 1i64;
    base %= modulus;
    while exp > 0 {
      if exp & 1 == 1 {
        result = result * base % modulus;
      }
      exp >>= 1;
      base = base * base % modulus;
    }
    result
  }
}