入坑codewars第16天-Transformation of a Number Through Prime Factorization
阿新 • • 發佈:2018-12-21
題目:
Every natural number, n
, may have a prime factorization like:
We define the geometric derivative of n, as a number with the following value:
For example: calculate the value of n*
for n = 24500
.
24500 = 2²5³7²
n* = (2*2) * (3*5²) * (2*7) = 4200
Make a function, f
f(n) ----> n*
Every prime number will have n* = 1
.
Every number that does not have an exponent ki
, higher than 1, will give a n* = 1
, too
f(24500) == 4200
f(997) == 1
Do your best!
題意:
題意就是按照那些公式算;首先把一個數分解成質因數相乘;然後按照第二個公式計算即可。
思路:
思路就是先分解成質因數相乘,然後儲存在列表裡;
然後利用列表的計數函式,計算出每個質因子的個數就是kn;
按照公式求就ok了
第一次提交的程式碼如下超時了:
import math from collections import Counter def f(n): m=n nn=1 list1=[] for i in range(2,m): while m%i==0: m=m/i list1.append(i) result = Counter(list1) for key in result: nn=nn*(result[key]*(key**(result[key]-1))) if m==n:return 1 return nn
我之前寫過類似的知道超時原因是什麼? 就是這個m太大會導致超時,解決辦法就是處理一下m變成根號m:
import math
from collections import Counter
def f(n):
m=n
nn=1
list1=[]
for i in range(2,int(math.sqrt(m))+1):
while m%i==0:
m=m/i
list1.append(i)
result = Counter(list1)
for key in result:
nn=nn*(result[key]*(key**(result[key]-1)))
if m==n:return 1
return nn
然後就可以了。