Skip to content

Commit e7101da

Browse files
committed
solutions: 1922 - Count Good Numbers (Medium)
1 parent 39dc9d1 commit e7101da

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
description: 'Author: @wkw | https://leetcode.com/problems/count-good-numbers'
3+
tags: [Math, Recursion]
4+
---
5+
6+
# 1922 - Count Good Numbers (Medium)
7+
8+
## Problem Link
9+
10+
https://leetcode.com/problems/count-good-numbers
11+
12+
## Problem Statement
13+
14+
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).
15+
16+
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.
17+
18+
Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo $1e9 + 7$.
19+
20+
A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
21+
22+
**Example 1:**
23+
24+
```
25+
Input: n = 1
26+
Output: 5
27+
Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8".
28+
```
29+
30+
**Example 2:**
31+
32+
```
33+
Input: n = 4
34+
Output: 400
35+
```
36+
37+
**Example 3:**
38+
39+
```
40+
Input: n = 50
41+
Output: 564908303
42+
```
43+
44+
**Constraints:**
45+
46+
- $1 <= n <= 1e15$
47+
48+
## Approach 1: Math
49+
50+
For even indices, good numbers can only include $0, 2, 4, 6, 8$. For odd indices, $2 ,3, 5, 7$ are good. Given a string of length $n$, it has $n + 1 // 2$ even indices and $n // 2$ odd indices. Thefore, the number of good numbers is simply $(5 ^ {(n + 1) / 2}) * (4 ^ {(n / 2)})$. Since $n$ can be up to $10 ^ {15}$, built-in $pow$ will cause TLE. We need to use [Binary Exponentiation](../../tutorials/math/number-theory/binary-exponentiation) to optimize it.
51+
52+
<Tabs>
53+
<TabItem value="py" label="Python">
54+
<SolutionAuthor name="@wkw"/>
55+
56+
```py
57+
class Solution:
58+
def countGoodNumbers(self, n: int) -> int:
59+
M = 10 ** 9 + 7
60+
# Binary Exponentiation
61+
def fastpow(b, exp, m):
62+
res = 1
63+
while exp > 0:
64+
if exp & 1: res = (res * b) % m
65+
b = (b * b) % m
66+
exp >>= 1
67+
return res
68+
# even: 0, 2, 4, 6, 8
69+
# odd: 2, 3, 5, 7
70+
# ways: (5 ** (n + 1) // 2) * (4 ** (n // 2))
71+
return (fastpow(5, (n + 1) // 2, M) * fastpow(4, n // 2, M)) % M
72+
```
73+
74+
</TabItem>
75+
</Tabs>

0 commit comments

Comments
 (0)