设x是一个满足要求的初值,经过这一系列操作后所得的数是y,则容易验证
$$y=\frac{4194304}{3^{30}}x-\frac{21110037246199}{3^{30}},$$
其中30是操作步骤字符串UDDDUdddDDUDDddDdDddDDUDDdUUDd的长度。整理后得
$$4194304x-3^{30}y=21110037246199,$$
用辗转相除法即可解得结果$1125977393124310$。
from fractions import Fraction
def extGCD(a,b):
if b==0:return a,1,0
d,x,y=extGCD(b,a%b)
return d,y,x-(a//b)*y
k,b=Fraction(1),Fraction(0)
for c in "UDDDUdddDDUDDddDdDddDDUDDdUUDd":
if c=="U":
k=k*4/3
b=(b*4+2)/3
elif c=="D":
k=k/3
b=b/3
else:
k=k*2/3
b=(b*2-1)/3
a,b,c=k.numerator,b.denominator,-b.numerator
d,x,y=extGCD(a,b)
x=x*c%b
print(x+(10**15-x+b-1)//b*b)
|