nayuki / Project-Euler-solutions

Runnable code for solving Project Euler problems in Java, Python, Mathematica, Haskell.
https://www.nayuki.io/page/project-euler-solutions
1.89k stars 675 forks source link

Crazy Magic, #26 #21

Closed brenschi closed 5 years ago

brenschi commented 5 years ago

Hi, I'm trying to understand what kind of crazy magic you're using for the twenty-sixth problem, specifically this little black box of black magic:

def reciprocal_cycle_len(n):
    seen = {}
    x = 1

    for i in itertools.count():
        if x in seen:
            return i - seen[x]
        else:
            seen[x] = i
            x = x * 10 % n

It's the simplest thing I've ever seen that I just can't figure out. I guess I'm just not good with numerology. Is there a spatial relationship that would make sense?

nayuki commented 5 years ago

It is a finite state machine that simulates dividing 1.000000... by n. In each iteration, x is the current remainder in the division, which is an integer between 1 and n-1 (inclusive).

This thread is about your understanding of math and logic, not an issue with my program. Please direct any further questions you have to a public volunteer forum such as https://stackoverflow.com/questions/ask or https://math.stackexchange.com/questions/ask .

brenschi commented 5 years ago

It is a finite state machine that simulates dividing 1.000000... by n. In each iteration, x is the current remainder in the division, which is an integer between 1 and n-1 (inclusive).

Thanks, bro.