- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminimum_factorization.py
More file actions
Latest commit
35 lines (30 loc) · 1.03 KB
/
Copy pathminimum_factorization.py
File metadata and controls
35 lines (30 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
给定一个正整数n,找到最小的正整数b,使得b的从左到右每位数字相乘结果等于n
"""
importunittest
defsolution(n: int) ->int:
res=''
# 贪心算法: 由于是每位数字的乘积,所以因数范围只可能是[2,9],为了让b尽可能小,所以要让较大的因数9尽可能排在个位,所以要先除以9
# 一定要让较大的因数先被除,避免48被分解成22223
forkinrange(9, 1, -1):
whilen%k==0:
# 注意结果是先塞入较大因数,所以后面要逆序
# 或者写成 res = str(k) + res 的方式逆序插入
res+=str(k)
n//=k
# n是质数的情况
ifn!=1:
return0
res_int=int(res[::-1])
ifres_int>0x7fffffff:
return0
else:
returnres_int
classTesting(unittest.TestCase):
TEST_CASES= [
(48, 68),
(15, 35)
]
deftest(self):
forn, expectedinself.TEST_CASES:
self.assertEqual(expected, solution(n))