尤拉計劃749:近似冪和

lt發表於2021-02-28

一個正整數n,其10進製表達的每位的正整數k次方的和,如果等於n-1或n+1,稱為近似冪和。比如,35是近似冪和,因為3^2 + 5^2 =34。
設s(n)為小於或等於n位的近似冪和的總和。
已知s(2)=100,s(6)=2562701。
求s(16)

測試程式

import time

def c(n):
 s=0
 for i in range(1,10**n):
  for j in range(2,20):
   s2=0
   for k in range(0,n):
    s2+=(i//(10**k)%10)**j
   if s2-i in [-1,1]:
    s+=i
    print(i,j,s2)
 return s

t=time.time();print(c(6));print(time.time()-t)

>>>> t=time.time();print(c(6));print(time.time()-t)
35 2 34
75 2 74
528757 6 528756
629643 6 629642
688722 6 688721
715469 6 715468
2562701
32.401257038116455

把各位的冪先加起來,然後看結果又沒有落在範圍內的

import itertools as it
def c2(n):
 s=0
 for d in range(2,n+1): #位數
  for k in range(2,20): #次方
   for i in it.combinations_with_replacement(range(0,10),d):
    if i[0]==0:continue
    #print(i)
    s2=0
    ls1=[str(ii) for ii in i];ls1.sort()
    for j in i:
     s2+=j**k
     if s2>10**d:break
    if s2<10**(d-1) or s2>10**d:continue
    ls2=list(str(s2-1));ls2.sort()
    ls3=list(str(s2+1));ls3.sort()
    if ls1==ls2 or ls1==ls3:
     if ls1==ls2:s2-=1
     else:s2+=1
     s+=s2
     print(i,k,s2)
 return s

>>>> t=time.time();print(c2(6));print(time.time()-t)
(3, 5) 2 35
(5, 7) 2 75
(1, 4, 5, 6, 7, 9) 6 715469
(2, 2, 6, 7, 8, 8) 6 688722
(2, 3, 4, 6, 6, 9) 6 629643
(2, 5, 5, 7, 7, 8) 6 528757
2562701
0.12479996681213379

相關文章