Project Euler #70: Totient permutation

  • + 0 comments

    This gives me a timeout error on 5 cases. Can anyone help?

    from math import gcd
    from itertools import permutations
    
    def totatives(n):
        phi = int(n > 1 and n)
        for p in range(2, int(n ** .5) + 1):
            if not n % p:
                phi -= phi // p
                while not n % p:
                    n //= p
        #if n is > 1 it means it is prime
        if n > 1: phi -= phi // n 
        return phi
    
    def permute(num,phi_num):
        temp="".join(sorted(str(num)))
        phi_num="".join(sorted(str(phi_num)))
        return temp==phi_num
    
    N=int(input())
    d={}
    for n in range(12,N):
        if permute(n,totatives(n)):
            #print(permute,phi(n))
            d[n]=(n/totatives(n))
        
    #print(d)
    min_b=min(d.values())
    for a,b in d.items():
        if b==min_b:
            print(a)
            break