有效解决Python中的字母/数字问题

Rob*_*Dey 8 python math

如果a = 15152表示为a2while,215则表示为2a必须找到数字x

8x = 8*x8

我试过这个天真的Python代码

>>> i = 0
>>> while(i<=100000000000000000):
...   if(int("8"+str(i))==8*int(str(i)+"8")):
...     break
...   i = i+1
... print i
Run Code Online (Sandbox Code Playgroud)

但是要花费大量时间才能产生正确的结果.

如何优化代码?

Phi*_*ipp 10

这里有一点数学帮助:设x是一个带n位数的自然数.然后8x = 8*10 ^ n + x,并且x8 = 10*x + 8.因此要求解的等式是8*10 ^ n + x = 8*(10*x + 8)= 80*x + 64 ,其中xn必须是自然数.紧接着x =(8*10 ^ n - 64)/ 79.现在我们只需要检查8*10 ^ n - 64形​​式的哪个数字可以被79整除,这非常快:

>>> n = 0
>>> while True:
...     y = 8 * 10**n - 64
...     if y % 79 == 0:
...         x = y / 79
...         break
...     n += 1
... 
>>> print x
101265822784
>>> print int("8"+str(x))==8*int(str(x)+"8")
True
Run Code Online (Sandbox Code Playgroud)