- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprime_factorization.py
More file actions
Latest commit
36 lines (30 loc) · 1.03 KB
/
Copy pathprime_factorization.py
File metadata and controls
36 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
36
"""
分解质因数算法:
枚举质因子 i 从最小的质数2开始到取整sqrt(num),因为比根号n还要大的因数容易成小数
依次判断 i 是否为 num 的因数
如果是那么存下 i 并且 num/=i ,继续判断
"""
importunittest
fromtypingimportList
# TODO 质因数分解有一种更快的算法,叫做Pollard Rho快速因数分解
# 根号n的算法: 分解质因数、分块检索法(drop_eggs_1)
defmy_solution(n: int) ->List[int]:
# 向上取整
upper_limit=int(n**0.5+1)
result= []
forkinrange(2, upper_limit):
whilen%k==0:
result.append(k)
n//=k
# 如果最后还有剩余,则为最后一个质因数,例如10的第二个质因数5
ifn!=1:
result.append(n)
returnresult
classTesting(unittest.TestCase):
TEST_CASES= [
(660, [2, 2, 3, 5, 11]),
(10, [2, 5]),
]
deftest(self):
forn, prime_factorsinself.TEST_CASES:
self.assertEqual(prime_factors, my_solution(n))