Algo-Sim › Math & Geometry

Count Good Numbers (mod 1e9+7)

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Count by multiplying choices, then compute 5^a · 4^b with modular fast power. Why 1e9+7: a prime whose square still fits in 64 bits.

Problem

A digit string is good if digits at even indices are even and digits at odd indices are prime (2, 3, 5 or 7). Given n, return the number of good digit strings of length n (leading zeros allowed), modulo 10⁹ + 7.

Constraints

Edge cases to test

Follow-up questions

Why 10⁹ + 7?
It is prime (so inverses exist) and two residues multiply to under 2⁶³, so 64-bit arithmetic never overflows.
How would you count with a forbidden pattern too?
A digit DP or an automaton over the pattern, raised to the n-th power with matrix fast power.

Solution

Java

private static final long MOD = 1_000_000_007L;

public int countGoodNumbers(long n) {
    long evens = (n + 1) / 2, odds = n / 2;
    return (int) (power(5, evens) * power(4, odds) % MOD);
}

private long power(long base, long exp) {
    long result = 1;
    base %= MOD;
    while (exp > 0) {
        if ((exp & 1) == 1) result = result * base % MOD;
        base = base * base % MOD;
        exp >>= 1;
    }
    return result;
}

Python

MOD = 10**9 + 7


def count_good_numbers(n):
    evens, odds = (n + 1) // 2, n // 2
    return power(5, evens) * power(4, odds) % MOD


def power(base, exp):
    # Python's built-in pow(base, exp, MOD) does exactly this.
    result = 1
    base %= MOD
    while exp > 0:
        if exp & 1:
            result = result * base % MOD
        base = base * base % MOD
        exp >>= 1
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    long long MOD = 1'000'000'007L;

    int countGoodNumbers(long long n) {
        long long evens = (n + 1) / 2, odds = n / 2;
        return (int)(power(5, evens) * power(4, odds) % MOD);
    }

    long long power(long long base, long long exp) {
        long long result = 1;
        base %= MOD;
        while (exp > 0) {
            if ((exp & 1) == 1)
                result = result * base % MOD;
            base = base * base % MOD;
            exp >>= 1;
        }
        return result;
    }
};

More Math & Geometry problems