证明冰雹猜想(Collatz 猜想)
3546165164posted 5 days agofor github.com/kisspeople/collatz-conjecture On the list
| 1 | """Write the request's example and check its two backwards odd blocks.""" |
| 2 | import csv |
| 3 | from pathlib import Path |
| 4 | |
| 5 | |
| 6 | def collatz_step(n): |
| 7 | return n // 2 if n % 2 == 0 else 3*n + 1 |
| 8 | |
| 9 | |
| 10 | def main(): |
| 11 | values = [6] |
| 12 | for _ in range(8): |
| 13 | values.append(collatz_step(values[-1])) |
| 14 | expected = [6, 3, 10, 5, 16, 8, 4, 2, 1] |
| 15 | if values != expected or 1 in values[:-1]: |
| 16 | raise ValueError("The forward trace differs from the supplied example") |
| 17 | |
| 18 | target = 1 |
| 19 | for exponent in (4, 1): |
| 20 | numerator = (2**exponent) * target - 1 |
| 21 | odd_parent, remainder = divmod(numerator, 3) |
| 22 | if remainder or odd_parent % 2 != 1: |
| 23 | raise ValueError("Invalid odd predecessor") |
| 24 | target = odd_parent |
| 25 | if 2*target != values[0]: |
| 26 | raise ValueError("The backwards reconstruction missed the start") |
| 27 | |
| 28 | output = Path(__file__).resolve().parent / "out" / "sample-6.csv" |
| 29 | output.parent.mkdir(exist_ok=True) |
| 30 | with output.open("w", encoding="utf-8-sig", newline="") as f: |
| 31 | table = csv.writer(f, lineterminator="\n") |
| 32 | table.writerow(["已走步数", "当前值", "下一步"]) |
| 33 | for i, value in enumerate(values): |
| 34 | rule = "到达 1" if i == 8 else ("除以 2" if value % 2 == 0 else "乘 3 再加 1") |
| 35 | table.writerow([i, value, rule]) |
| 36 | print("6 -> 1: 8 steps, first hit; inverse blocks (4, 1) recover 6.") |
| 37 | |
| 38 | |
| 39 | if __name__ == "__main__": |
| 40 | main() |