DESCRIPTION:
Some numbers have funny properties. For example:89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51Given a positive integer n written as abcd... (a, b, c, d... being digits) and a >positive integer p
we want to find a positive integer k, if it exists, such that the sum of the digits of >n taken to the successive powers of p is equal to k * n.
In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * kIf it is the case we will return k, if not return -1.
Note: n and p will always be given as strictly positive integers.
題目理解:給定一個正整數n以及n,先將n其每個位數拆分(Ex:abcd...)。
再依序將a^p,b^(p+1),c^(p+2),d^(p+d)...相加得到一個總和,若此總和乘上某正整數k恰可以等於n本身,則函式返還k,否則返還-1。
def dig_pow(n, p):
num_lst = [ i for i in str(n) ] #先將數字照原順序拆分成列表儲存
sum = 0
pow = p
for i in range(len(num_lst)): #逐一計算每個位數的次方和
sum += int(num_lst[i])**pow
pow +=1
if sum % n == 0: #若能sum能被n整除,代表存在正整數k
return int(sum/n) #故返還k = sum/n
return -1