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
- 1 ≤ n ≤ 10¹⁵
- Answer modulo 10⁹ + 7
Edge cases to test
- n = 1:
5 - Huge n (needs modular fast power)
- Odd vs even n
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 resultC++
#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
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)