Project Euler #70: Totient permutation

  • + 0 comments

    def sieve_of_eratosthenes(limit): primes = [True] * (limit + 1) primes[0], primes[1] = False, False

    p = 2
    while p * p <= limit:
        if primes[p]:
            for i in range(p * p, limit + 1, p):
                primes[i] = False
        p += 1
    
    return [i for i in range(2, limit + 1) if primes[i]]
    

    def phi(n, primes): result = n for p in primes: if p * p > n: break if n % p == 0: while n % p == 0: n //= p result -= result // p if n > 1: result -= result // n return result

    def is_permutation(a, b): return sorted(str(a)) == sorted(str(b))

    def find_min_ratio(limit): primes = sieve_of_eratosthenes(4000) # Considering primes up to a limit

    min_ratio = float('inf')
    min_n = 0
    
    for i in range(len(primes)):
        for j in range(i, len(primes)):
            n = primes[i] * primes[j]
            if n > limit:
                break
            totient = phi(n, primes)
            if is_permutation(n, totient):
                ratio = n / totient
                if ratio < min_ratio:
                    min_ratio = ratio
                    min_n = n
    
    return min_n
    

    Taking input

    limit = int(input())

    Finding and printing the answer

    result = find_min_ratio(limit) print( result)