def totient2(n): try: return d_totient[n] except KeyError: ret = n if is_prime(n): ret = n - 1 else: fact = prime_factors(n) for p in fact: ret = ret*(p - 1)/p k = 1 while True: d_totient[n**k] = (n**(k - 1))*ret k += 1 if n**k >= 10**6: break return d_totient[n]
def test0003(self): from id_0003 import is_prime, prime_factors primes = [2, 3, 5, 7, 11, 13, 17] for x in primes: self.assertEqual(is_prime(x), 1) non_primes = [4, 6, 8, 10, 12, 14, 15, 16, 18] for x in non_primes: self.assertEqual(is_prime(x), 0) self.assertEqual(prime_factors(2), [2]) self.assertEqual(prime_factors(3), []) self.assertEqual(prime_factors(4), [2]) self.assertEqual(prime_factors(5), []) self.assertEqual(prime_factors(6), [2, 3]) self.assertEqual(prime_factors(10), [2, 5]) self.assertEqual(prime_factors(13195), [5, 7, 13, 29])