Skip to content

Instantly share code, notes, and snippets.

@liweinan
Created August 29, 2025 12:51
Show Gist options
  • Save liweinan/36b781005c0ec5a5372c823672fc39aa to your computer and use it in GitHub Desktop.
Save liweinan/36b781005c0ec5a5372c823672fc39aa to your computer and use it in GitHub Desktop.
def f_iterative(x):
stack = [(x, 0)] # (参数, 状态): 0=初始, 1=等待内层f(x-0.5), 2=等待外层f(x-f(x-0.5))
results = {} # 缓存中间结果,避免重复计算
while stack:
x, state = stack.pop()
if x < 0:
results[x] = -x
continue
if state == 0:
# 初始状态,计算f(x-0.5)
stack.append((x, 1))
if x - 0.5 not in results:
stack.append((x - 0.5, 0))
elif state == 1:
# 已得到f(x-0.5),计算f(x - f(x-0.5))
inner_result = results.get(x - 0.5)
next_x = x - inner_result
stack.append((x, 2))
if next_x not in results:
stack.append((next_x, 0))
elif state == 2:
# 已得到外层结果,计算0.5 * f(next_x)
inner_result = results.get(x - results.get(x - 0.5))
results[x] = 0.5 * inner_result
return results[x]
def g(x):
import math
f_x = f_iterative(x)
return -math.log2(f_x) if f_x > 0 else float('inf')
# 计算g(4) mod 4
try:
result = g(4) % 4
print(result)
except RecursionError:
print("Recursion depth exceeded")
@liweinan
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment