Competitive/Collaborative Programming Class

ICPC Computer Programming Contest Prep

Problem Solving in Computer Science

Spring 2023 -- CSC 2700 Section 01 (1216 Patrick Taylor, 6:30 PM - 8:20 PM)



Number Theory

To borrow from Programming Challenges, number theory in programming contests includes the following:

References


Primes

In general, I believe 99% of dealing with primes in a problem boils down to loading a list with the first N prime numbers via the Sieve of Erasthones:

    primeCnt = 0;
    for (i=0; i< UPPERLIMIT; i++) a[i] = i;
    for (i=2; i<UPPERLIMIT; i++)
     { /* for */
        if (0 != a[i])
         { /* found a prime */
            p[primeCnt] = i;
            primeCnt++;
            for (j=i*2; j < UPPERLIMIT; j=j+i) a[j] = 0;
         } /* found a prime */
     } /* for */ 

Of course, what do you do with the list? Using it to determine prime factors might be common.


Divisibility

In one sense divisibility is easy -- use mod. Here are some neat rules for divisibility:


Modular Arithmetic

Modular arithmetic is sometimes called clock arithmetic. It is the idea that the set of numbers is finite and that you wrap to the begining when you go past the end (like a clock does). Lots of problems rely on these ideas (such as the "every nth person out" problems).

A typical code snippet might be something like:

n = (n + 1) mod MAX

When you think about it, this is how all arithmetic works. 9 + 1 = 10 When you add one to the largest base 10 digit (9) you get zero for an answer with a carry into the next column. You do the same in modular arithmetic except for forget the carry.