UVic Programming Club

Prime Numbers

Check if a number is prime

def is_prime(n):
    if n < 5:
        return n == 2 or n == 3
    if not (n % 6 == 1 or n % 6 == 5):
        return False
    for m in range(5, int(n ** 0.5) + 1, 6):
        if not (n % m and n % (m + 2)):
            return False
    return True

Generate prime numbers up to n

    vector<bool> primes(n + 1, true);
    primes[1] = false;

    int p = 2;
    while (p * p <= n) {
        if (primes[p]) {
            for (int i = p * p; i <= n; i += p)
                primes[i] = false;
        }
        p += 1;
    }

Big mod

    long long int bigmod(long long int b, long long int p, long long int m)
    {
        if(p == 0)  return 1;
        if((p % 2) == 0)
        {
            long long int temp = bigmod(b, p / 2, m);
            return (temp * temp) % m;
        }
        return (bigmod(b, p - 1, m) * (b % m)) % m;
    }
  1. Happy Happy Prime Prime
  2. Checking For Correctness
  3. Blackboard Numbers
  4. Prime Sieve : Sieve of Eratosthenes