取任何正数,反复减去它的反射,直到零。喜欢,
275-572 = -297
297-792 = -495
495-594 = -99
99-99 = 0它声称所有的数字都以这种方式收敛到0(除了某个数字和它的倍数),所以我想测试这个,但是我不是一个程序员,从高中开始我就没有碰过python了:D
到目前为止,我所做的只是从interwebz偷了一个函数;
def r(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r此函数返回一个反射整数。现在我需要某种循环或递归函数,但是我什么都想不出来。有什么帮助吗?
发布于 2022-08-10 09:25:23
def my_func(x):
while x != 0: # We stop when x is 0 since that is our destination
print(f"number @ current step: {x}")
x = abs(x - r(x)) # subtract the reflection and get rid of the negative sign (if it is negative)现在,如果一个数字没有收敛到零,my_func就不会终止。
以下是检测无限循环的改进:
# returns True if 0 is reached, False if it never reaches 0.
def my_func(x):
cache = set()
while x != 0: # We stop when x is 0 since that is our destination
# print(f"number @ current step: {x}")
x = abs(x - r(x)) # subtract the reflection and get rid of the negative sign (if it is negative)
if x in cache:
print(f"This number does not terminate!")
return False
cache.add(x)
return True在测试了0到999之间的数字之后,我发现没有一个不收敛到0的数字。
发布于 2022-08-10 11:39:21
通过对全局数组缓存中测试的所有数字进行标记,solution of MMZK1526可以进一步优化运行时速度,从而降低内存消耗。
def reflect(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r
upper_bound = pow(10, 6) - 1
# Result cache for all tested numbers, pre-initialize the array with zeroes.
cache = [0 for i in range(upper_bound + 1)]
def test(n):
if n == 0:
return True
if cache[n] == 1:
# Early out because we already know n does converge.
return True
if cache[n] == 2:
# Loop in current recursion detected, so n does not converge.
cache[n] = 3
return False
if cache[n] == 3:
# n has previously been marked as non-converging.
cache[n] = 3
return False
# Temporarily mark numbers in current recursion (2)
cache[n] = 2
if test(abs(n - reflect(n))):
# Mark n as converging (1).
cache[n] = 1
return True
else:
# Mark n as non-converging (3).
cache[n] = 3
return False
converging = 0
non_converging = 0
for i in range(1, upper_bound):
if test(i):
converging += 1
else:
non_converging += 1
print(f'{converging} converging and {non_converging} failing.')当测试1..999999中的所有数字时,我在1.328秒内得到515419 converging and 484579 failing,而非缓存的方法在我的机器上使用9.411 s。
发布于 2022-08-10 09:31:35
该算法需要以腹肌为基础进行。
def r(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r
input_number = 275
max_iters = 100 # don't want to run infinitely if it does not converge
iters = 0
while( input_number != 0 and iters < max_iters ):
#debug, if you wish
print(input_number, " - ", r((input_number)))
input_number = abs( input_number - r(input_number))
iters += 1https://stackoverflow.com/questions/73303733
复制相似问题