Python求解质数因子的方法
质数因子(Prime Factors)是指一个正整数可以分解为一系列质数的乘积。例如:
12的质数因子是2, 2, 3(因为12 = 2 × 2 × 3)
30的质数因子是2, 3, 5(因为30 = 2 × 3 × 5)
每个大于1的整数要么本身是质数,要么可以表示为质数的乘积,这就是算术基本定理。
|
factors = [] divisor = 2 while divisor <= n: if n % divisor == 0: factors.append(divisor) n = n // divisor #整数除法(地板除) else: divisor += 1 return factors # 示例 print(prime_factors(12)) # 输出: [2, 2, 3] print(prime_factors(30)) # 输出: [2, 3, 5] print(prime_factors(17)) # 输出: [17] |
res = [] while a>1: for i in range(2,a+1): if a%i == 0: res.append(i) a = int(a/i) break return res print(primeFactor(12)) # 输出: [2, 2, 3] print(primeFactor(30)) # 输出: [2, 3, 5] print(primeFactor(17)) # 输出: [17] print('8/5:',8/5,'5/2:',5/2) # 输出:8/5: 1.6 5/2: 2.5 print('8//5:',8//5,'5//2:',5//2)#输出: 8//5: 1 5//2: 2
|
print(prime_factors(315)) # 输出: [3, 3, 5, 7]
print(prime_factors(100)) # 输出: [2, 2, 5, 5]
factors[divisor] = factors.get(divisor, 0) + 1
print(prime_factors(12)) # 输出: {2: 2, 3: 1}
print(prime_factors(100)) # 输出: {2: 2, 5: 2}
print(factorint(12)) # 输出: {2: 2, 3: 1}
print(factorint(1000000000000000000)) # 输出: {2: 18, 5: 18}

浙公网安备 33010602011771号