返回 2026-06-28
⚙️ 工程

a/b 的小数何时开始循环?When will the decimals in a/b repeat?

johndcook.com·2026-06-27 节选正文

分数 a/b 转化为小数后,其循环周期的长度是一个经典的数论问题。作者通过编写和提供具体的代码,探讨了分数小数部分的循环节长度规律。文章还结合了之前关于调和数的讨论,深入分析了数字周期背后的数学基础。这些代码和分析为处理分数和计算周期提供了实用的编程工具。读者可以借此快速计算出任意分数的循环周期。

John

The previous post looked at how many digits are in the reduced fraction for the nth harmonic number. I was curious about how long the cycle of digits in a harmonic number might be.

I wrote about the period length for the digits of fractions almost a decade ago. This post includes code so I can apply it to harmonic demoninators.

from sympy import lcm, factorint, n_order

def period(n):
    factors = factorint(n)
    exp2 = factors.get(2, 0)
    exp5 = factors.get(5, 0)
    r = max(exp2, exp5)

    d = n // (2**exp2 * 5**exp5)
    s = 1 if d == 1 else n_order(10, d)
    return (r, s)

This function returns two numbers: r is the number of non-repeating digits at the beginning and s is the length of the repeating part.

The following code

from functools import reduce

def lcm_range(n):
    return reduce(lcm, range(1, n + 1))

print( period( lcm_range(50) ) )

prints (5, 1275120) meaning that 1/lcm(1, 2, 3, …, 49, 50) has five non-repeating digits following by 1,275,120 digits that repeat ad infinitum. And so the decimals in the expansion of H50 go have a cycle length of 1,275,120.

需要完整排版与评论请前往来源站点阅读。