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.
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 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)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #70: Totient permutation
You are viewing a single comment's thread. Return to all comments →
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)