Project Euler #65: Convergents of e

  • + 0 comments

    python solution

    from math import isqrt
    
    num, den, two = 1, 1, 2
    
    def sum_of_digits(n):
        s = 0
        while n:
            s, n = s + n % 10, n // 10
        return s
    
    def reciprocal():
        global num, den
        num, den = den, num
    
    def add_number_to_fraction(x):
        global num
        num = den * x + num
    
    g = int(input())
    if g == 1:
        print(2)
    elif g == 2:
        print(3)
    else:
        given = g
        three = 3
        num = (given // three) * two
        a = num - two
        if given % three == 1:
            num += 1
        elif given % three == 2:
            num = num * 2 + 1
            den = 2
        given -= given % three
        reciprocal()
        while given > 3:
            if given % three != 1:
                add_number_to_fraction(1)
            else:
                add_number_to_fraction(a)
                a -= two
            reciprocal()
            given -= 1
        add_number_to_fraction(1)
        reciprocal()
        add_number_to_fraction(2)
        print(sum_of_digits(num))