We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Project Euler #70: Totient permutation
Project Euler #70: Totient permutation
Sort by
recency
|
16 Discussions
|
Please Login in order to post a comment
C++ Solution:
my code is failing due to optimization problems ,how can i further optimize this code or use a different approach
def sieve_of_eratosthenes(limit): primes = [True] * (limit + 1) primes[0], primes[1] = False, False
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
Taking input
limit = int(input())
Finding and printing the answer
result = find_min_ratio(limit) print( result)
This gives me a timeout error on 5 cases. Can anyone help?
I am one of those who approach the problem using the property that is minimum when it is prime. And because is never the permutation of prime , so we set our sight on being the product of two primes and . (Hint on counting: )
For my implementation, I used a prime sieve to generate a list of primes, and feed them to a 2-level for loop afterwards. The point here is the find a balance between reducing the size of prime sieve (otherwise it would be TLE if we make a sieve of size ) and whether we have enough primes to get to the answer. For example, one of the answers is (product of and ), so we need to ensure is included in the prime sieve when is .
Apart from that, we have one honourable candidate who is an answer, but is not the product of two prime numbers, but three! This is the frustrating Test Case #10. I don't have a strategy yet to handle this other than treating it as a special case.