CSE 40872 Lecture 018

Topic:Number Theory (Primes)
Author: Peter Bui <pbui@cse.nd.edu>
Date: October 28, 2009

Number Theory

Study of the properties and characteristics of numbers, in this case integers.

Lots of possible topics: primes, divisbility (GCD, LCM), modular arithmetic, congruences.

Primes

A prime number is an integer p > 1 which is only divisible by 1 and itself:

2 3 5 7 11 13 17

Non-primes are called composite numbers.

Fundamental theorem of arithmetic: Every integer can be expressed in only one way as a product of primes.

Finding Primes

Simply try to divide all integers from 2 to sqrt(n) + 1

static int is_prime(int n) {
    int i;

    if (n == 2)
        return TRUE;

    for (i = 2; i < sqrt(n) + 1; i++)
        if ((n % i) == 0)
            return FALSE;

    return TRUE;
}

Prime Factorization

static void prime_factorization(int n) {
    int i;

    while ((n % 2) == 0)
        printf(" %d", 2); n /= 2;

    i = 3;
    while (i < (sqrt(n) + 1)) {
        if ((n % i) == 0)
            printf(" %d", i); n /= i;
        else
            i += 2;
    }

    if (n > 1) printf(" %d", n);
}

Compute Primes

Set all elements in Prime array to TRUE, and then go through composites and mark them as FALSE.

static void compute_primes(int n) {
    int i, j;

    for (i = 0; i < n; i++)
        Prime[i] = TRUE;

    for (i = 2; i < n; i++)
        for (j = 2; j < n && (i * j) < n; j++)
            Prime[i * j] = FALSE;
}