Start free

Beyond A level · 7 exercises

Python number theory

Whole-number tricks: n % d == 0 means d divides n; test divisors only up to the square root; the sieve of Eratosthenes finds every prime up to n at once.

pow(a, b, m) works out a to the power b, modulo m, quickly, even when the power is huge.

n = 50
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
    if is_prime[i]:
        for j in range(i * i, n + 1, i):
            is_prime[j] = False
print(sum(is_prime))

Watch for: Testing every number up to n one by one is too slow for big inputs: the hidden tests notice.

Exercises

  1. Counting primes fastCount the prime numbers up to n, for n as large as 2,000,000.Expert
  2. Huge powersCompute a to the power b, modulo m, where b can have 18 digits.Expert
  3. Prime factorsWrite a number as a product of primes, from smallest to largest, likeExpert
  4. Modular inverseFind x between 0 and m - 1 with a * x mod m = 1, using the extended EuclideanExpert
  5. Euler's totientCount how many numbers from 1 to n share no common divisor with n except 1.Expert
  6. Combinations modulo a primeCompute C(n, k), the number of ways to choose k items out of n, modulo 1000000007,Expert
  7. Any base to any baseConvert a number between bases 2 and 36.Expert
Start with “Counting primes fast”