代码如下:
# 质数判断函数
def is_prime(num):
if num < 2:
return False
elif num == 2 or num == 3:
return True
else:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# 质因数分解函数
def prime_factorize(num):
if num < 2: # 非质数亦非合数
print('"%s" have no prime factor.' % num)
return 0
if is_prime(num): # 质数
print('"%s" is prime number!' % num)
return 0
else: # 合数
pri_fac_list = [] # 用于保存质因数
while 1:
if is_prime(num):
pri_fac_list.append(num)
break
for i in range(2, num//2 + 1):
if is_prime(i) and num % i == 0: # i既是质数又是因数
pri_fac_list.append(i)
num = num // i
# print('TEST:num = %s' % num)
break # 跳出for循环
print(pri_fac_list)
if __name__ == '__main__':
global n
try:
n = int(input('Enter a number:').strip()) # 输入待分解的数
except ValueError:
print('Error! Please input a number.') # 异常处理
exit(1)
prime_factorize(n)
注意:
若不用 “global n” 将n声明为全局变量,Pycharm将在 “prime_factorize(n)” 处提示警告:
Name 'n' can be not defined less... (Ctrl+F1)
This inspection warns about local variables referenced before assignment.
即赋值前引用局部变量。