题目要求:
给出指定数字的乘法分解,要求因子全为质数,如:n = 86240 should return "(2**5)(5)(7**2)(11)",**表示指数运算。
最初想法是先做小于 n 的质数表,再在循环中遍历质数表,寻找余数为 0 的质数。当 n 一大必然超时,超时的原因是计算了很多无用的质数,如 n=86240 我们最多需要到 11 的质数。
当 n 可以被一个质数整除时,会一直进行 n //= prime,知道不能整除为止再尝试下一个质数。
1 def solve(n): 2 d = dict() 3 num = 2 4 while n != 1: 5 if not n % num: 6 d[num] = d[num]+1 if d.get(num) else 1 7 n /= num 8 else: 9 num += 1 10 res = "" 11 for b,e in d.items(): 12 if e==1: 13 res += "(%d)"%b 14 else: 15 res += "(%d**%d)"%(b,e) 16 return res
浙公网安备 33010602011771号