"""Write the request's example and check its two backwards odd blocks.""" import csv from pathlib import Path def collatz_step(n): return n // 2 if n % 2 == 0 else 3*n + 1 def main(): values = [6] for _ in range(8): values.append(collatz_step(values[-1])) expected = [6, 3, 10, 5, 16, 8, 4, 2, 1] if values != expected or 1 in values[:-1]: raise ValueError("The forward trace differs from the supplied example") target = 1 for exponent in (4, 1): numerator = (2**exponent) * target - 1 odd_parent, remainder = divmod(numerator, 3) if remainder or odd_parent % 2 != 1: raise ValueError("Invalid odd predecessor") target = odd_parent if 2*target != values[0]: raise ValueError("The backwards reconstruction missed the start") output = Path(__file__).resolve().parent / "out" / "sample-6.csv" output.parent.mkdir(exist_ok=True) with output.open("w", encoding="utf-8-sig", newline="") as f: table = csv.writer(f, lineterminator="\n") table.writerow(["已走步数", "当前值", "下一步"]) for i, value in enumerate(values): rule = "到达 1" if i == 8 else ("除以 2" if value % 2 == 0 else "乘 3 再加 1") table.writerow([i, value, rule]) print("6 -> 1: 8 steps, first hit; inverse blocks (4, 1) recover 6.") if __name__ == "__main__": main()