Number Theory and Cryptography


Number Theory and Cryptography

Maria
Welcome to Chapter Four: number theory and cryptography. Number theory studies integers—the whole numbers, including negatives and zero—and cryptography is the mathematics of secret messages. We begin with a simple question: does one number divide another exactly? From there, we build toward primes, modular arithmetic, and the codes used to protect information.

Corey
The chapter has six connected topics: divisibility and modular arithmetic; representing integers in different bases; primes and greatest common divisors; solving congruences; applications of congruences; and cryptography. The ideas are beautiful in their own right, but they also have practical uses in computer science and internet security.

Maria
Let’s begin with divisibility. For integers a and b, with a not zero, we say a divides b if b equals a times some integer c. We write that as a vertical bar between a and b. So three divides twelve because twelve is three times four, but three does not divide seven because seven divided by three is not an integer.

Corey
When a divides b, a is a factor or divisor of b, and b is a multiple of a. Divisibility also has useful rules: if a divides both b and c, then it divides their sum; if a divides b, it divides b times any integer; and if a divides b and b divides c, then a divides c.

Maria
The sum rule follows directly from the definition. If b equals a times s and c equals a times t, then b plus c equals a times the quantity s plus t. Since s plus t is an integer, the sum is a whole-number multiple of a. More generally, a divisor shared by b and c divides every linear combination m times b plus n times c.

Corey
Next is the division algorithm, which is a theorem about quotients and remainders. For any integer a and positive integer d, there is exactly one pair of integers q and r such that a equals d times q plus r, with zero less than or equal to r and r less than d. The remainder is always nonnegative and smaller than the divisor.

Maria
For example, one hundred one divided by eleven has quotient nine and remainder two, because one hundred one equals eleven times nine plus two. Negative dividends need care. For negative eleven divided by three, we use negative four as the quotient and one as the remainder: negative eleven equals three times negative four plus one. A remainder of negative two would break the rule.

Corey
That remainder idea leads to congruence. We say a is congruent to b modulo m when m divides a minus b, where m is positive. In other words, a and b leave the same remainder when divided by m. The modulus m tells us the size of the steps between numbers in the same congruence class.

Maria
The clock is a useful picture. Three o’clock and fifteen o’clock point to the same position on a twelve-hour clock because their difference is twelve. So they are congruent modulo twelve. Likewise, seventeen is congruent to five modulo six, because their difference is twelve; but twenty-four is not congruent to fourteen modulo six, because their difference, ten, is not divisible by six.

Corey
There’s an equivalent way to express the definition: a is congruent to b modulo m exactly when a equals b plus k times m for some integer k. The integer k can be negative, so it describes moving forward or backward by whole steps of size m.

Maria
It helps to distinguish two uses of the word mod. In a congruence statement, mod names a relation between two numbers. In an expression such as a mod m, it means the function that returns the remainder. The two ideas connect: a and b are congruent modulo m if and only if their remainders upon division by m are equal.

Corey
Congruences are preserved by addition and multiplication. If a is congruent to b and c is congruent to d modulo m, then a plus c is congruent to b plus d, and a times c is congruent to b times d. That means we can replace a number with an equivalent remainder to make calculations easier.

Maria
For instance, modulo five, seven is equivalent to two and eleven is equivalent to one. So seven plus eleven is equivalent to two plus one, which is three; and seven times eleven is equivalent to two times one, which is two. You can add or multiply both sides by the same integer, but you cannot assume division is safe.

Corey
Here’s why division can fail. Fourteen is congruent to eight modulo six, since their difference is six. Divide both numbers by two and you get seven and four, but those are not congruent modulo six. Later, we’ll see the exact condition that permits cancellation.

Maria
For large calculations, reduce numbers before adding or multiplying. To find a product modulo m, take the remainder of each factor, multiply those smaller remainders, and reduce again. Arithmetic modulo m uses the set of remainders from zero through m minus one, so every answer stays inside that set.

Corey
This arithmetic keeps many familiar properties: it is closed under addition and multiplication, associative, and commutative. Zero is the additive identity, one is the multiplicative identity, every element has an additive inverse, and multiplication distributes over addition. But multiplicative inverses do not always exist: modulo six, no number multiplied by two gives a remainder of one.

Maria
Now let’s talk about how numbers are written. In base ten, each place represents a power of ten. For example, nine hundred sixty-five means nine times ten squared, plus six times ten, plus five. We can use any base greater than one; binary is base two, octal is base eight, and hexadecimal is base sixteen.

Corey
Every positive integer has a unique expansion in any chosen base: a sum of digits times powers of that base, with each digit between zero and one less than the base. The leading digit cannot be zero. Base ten is familiar, but history gives us other examples: the Maya used base twenty, and the Babylonians used base sixty, which still appears in our minutes and seconds.

Maria
Binary uses only zero and one, which suits computers that represent states such as off and on. Each position is a power of two. To convert a binary number to decimal, add the powers of two whose digits are one. For example, binary one-one-zero-one-one represents sixteen plus eight plus two plus one, or twenty-seven.

Corey
Octal uses the digits zero through seven, with places that are powers of eight. Hexadecimal uses sixteen digits: zero through nine, then A through F for ten through fifteen. The base matters—the digits one-one-one mean seven in binary, but seventy-three in octal.

Maria
To convert a positive integer into base b, repeatedly divide by b and record the remainders. The first remainder is the rightmost digit; then divide the quotient again and continue until the quotient is zero. Read the remainders in reverse order. For example, repeated division converts twelve thousand three hundred forty-five into octal three-zero-zero-seven-one.

Corey
Binary, octal, and hexadecimal have a particularly convenient relationship. Since eight is two cubed, one octal digit corresponds to exactly three bits. Since sixteen is two to the fourth, one hexadecimal digit corresponds to four bits. So converting between these bases only requires grouping binary digits in threes or fours, padding with leading zeros if needed.

Maria
Computers also use algorithms to do arithmetic on bits. For addition, process bits from right to left, adding the two bits and the carry. The result gives a sum bit and a new carry. Since the same small operation is performed at each of n bit positions, adding two n-bit integers takes order n bit operations.

Corey
Multiplication uses shifted partial products. For each one-bit in one factor, shift the other factor left by that bit’s position, which is the same as multiplying by a power of two; for a zero-bit, the partial product is zero. Adding the partial products takes order n squared bit operations for two n-bit numbers.

Maria
Large powers need a faster method. Write the exponent in binary, build successive squares of the base, and multiply only the powers that correspond to one-bits in the exponent. For example, eleven in binary is eight plus two plus one, so three to the eleventh is three to the eighth times three squared times three.

Corey
This repeated-squaring method is especially useful for computing b to the n modulo m. Reduce modulo m after each multiplication so the numbers stay small, and process one exponent bit at a time. The number of steps grows with the number of bits in n, rather than with n itself, which makes huge modular powers practical in cryptography.

Maria
Now to primes. A prime is a positive integer bigger than one whose only positive divisors are one and itself. A number bigger than one that is not prime is composite. One is neither. The Fundamental Theorem of Arithmetic says every integer bigger than one has a prime factorization, and that factorization is unique apart from the order of the factors.

Corey
You can picture primes as the atoms of whole numbers. For example, one hundred factors as two squared times five squared, and one thousand twenty-four is two to the tenth. To test whether a number is prime, it is enough to try prime divisors up to its square root: if a number is composite, at least one of its factors is no larger than the square root.

Maria
That fact explains the Sieve of Eratosthenes. List the numbers from two upward, keep the first number not crossed out, and cross out its multiples. For numbers up to one hundred, it is enough to cross out multiples of two, three, five, and seven, because those are the primes below the square root of one hundred.

Corey
Trial division uses the same square-root idea, but it becomes slow for very large numbers. Euclid’s proof that there are infinitely many primes is a different kind of argument. Suppose there were only finitely many, multiply all of them together, and add one. None of the listed primes divides that new number, so it must have a prime factor missing from the supposedly complete list—a contradiction.

Maria
Some primes and prime questions have special names. A Mersenne prime has the form two to the p minus one, where p is prime, and the result is prime. A prime exponent does not guarantee a Mersenne prime: two to the eleventh minus one is composite. But a fast test for Mersenne numbers helps researchers search for enormous primes.

Corey
The prime number theorem estimates how many primes are at most x: the count is approximately x divided by the natural logarithm of x, with the estimate improving as x grows. It also suggests that a randomly chosen number near n has probability about one over the natural logarithm of n of being prime. Primes grow rarer, but they never run out.

Maria
Many prime questions remain open. Goldbach’s conjecture says every even number bigger than two is a sum of two primes. The twin prime conjecture says there are infinitely many prime pairs that differ by two. We also believe infinitely many numbers of the form n squared plus one are prime, but that is unproved. Checking many examples is evidence, not proof.

Corey
The greatest common divisor, or gcd, is the largest positive integer that divides both of two integers. If their gcd is one, they are relatively prime. A list is pairwise relatively prime when every pair in it has gcd one; one pair that shares a factor is enough to make the whole list fail that condition.

Maria
If you know the prime factorizations, the gcd uses the smaller exponent of each prime, treating a missing prime as having exponent zero. The least common multiple, or lcm, uses the larger exponent. For example, one hundred twenty is two cubed times three times five, while five hundred is two squared times five cubed, so their gcd is two squared times five, or twenty.

Corey
The gcd and lcm satisfy a useful relationship: for positive a and b, a times b equals gcd of a and b times lcm of a and b. But factoring large numbers just to find a gcd is inefficient. The Euclidean algorithm finds it using division alone.

Maria
The Euclidean algorithm repeatedly replaces a pair by the divisor and the remainder. The gcd of a and b is the same as the gcd of b and the remainder when a is divided by b. For example, two hundred eighty-seven divided by ninety-one leaves fourteen; ninety-one divided by fourteen leaves seven; fourteen divided by seven leaves zero. The last nonzero remainder, seven, is the gcd.

Corey
Why does the algorithm work? If a equals b times q plus r, a number divides both a and b exactly when it divides both b and r. And the remainders keep getting smaller while staying nonnegative, so the process must eventually stop. The algorithm is fast even for very large integers.

Maria
Bézout’s identity says the gcd of a and b can always be written as s times a plus t times b, for some integers s and t. Those integers are Bézout coefficients. The Euclidean algorithm finds the gcd going forward; substituting the remainder equations backward expresses that gcd as a linear combination.

Corey
For example, the gcd of six and fourteen is two, and two equals negative two times six plus one times fourteen. Bézout’s identity also helps prove a key cancellation fact: if a and b are relatively prime and a divides b times c, then a divides c.

Maria
That cancellation fact gives the exact rule for dividing a congruence. If a times c is congruent to b times c modulo m, and c is relatively prime to m, then c can be cancelled, giving a congruent to b modulo m. Our earlier failed example had c equal to two and modulus six, which are not relatively prime.

Corey
Now we can solve congruences. A linear congruence has the form a times x congruent to b modulo m. If a and m are relatively prime, there is exactly one solution class modulo m. But solutions are not guaranteed in every case: two x congruent to three modulo six has no solution, while two x congruent to two modulo six has two classes.

Maria
The tool for solving is a multiplicative inverse. An inverse of a modulo m is a number a-bar such that a-bar times a is congruent to one modulo m. It exists exactly when a and m are relatively prime, and then it is unique modulo m. Once we have it, multiplying a congruence by the inverse safely removes the coefficient.

Corey
Bézout gives a way to find the inverse. If the gcd of a and m is one, then s times a plus t times m equals one. Modulo m, the term t times m disappears, leaving s times a congruent to one. So s is an inverse of a. For example, seven equals two times three plus one, so negative two—and equivalently five—is an inverse of three modulo seven.

Maria
To solve three x congruent to four modulo seven, multiply both sides by an inverse of three, such as negative two. That gives x congruent to six modulo seven. The complete answer is every integer in that class, such as six, thirteen, twenty, and also negative one. We can check it by substituting and reducing modulo seven.

Corey
For a system of congruences, the Chinese Remainder Theorem applies when the moduli are pairwise relatively prime. It guarantees one solution modulo the product of the moduli. “One solution” means one class: every other solution differs by a whole multiple of that product.

Maria
Sun-Tsu’s puzzle is a classic example: find x that leaves remainders two, three, and two when divided by three, five, and seven. The product of the moduli is one hundred five. Building the solution with the theorem gives twenty-three modulo one hundred five, and twenty-three checks against all three remainders.

Corey
There’s also a back-substitution method: turn the first congruence into an equation with a new integer variable, substitute into the second, then continue through the system. For remainders one modulo five, two modulo six, and three modulo seven, the method gives x congruent to two hundred six modulo two hundred ten.

Maria
Fermat’s Little Theorem is another shortcut for modular arithmetic. If p is prime and a is not divisible by p, then a to the power p minus one is congruent to one modulo p. A second form says a to the power p is congruent to a modulo p for every integer a.

Corey
The theorem reduces huge exponents. For example, modulo eleven, seven to the tenth is one. Since two hundred twenty-two is twenty-two times ten plus two, seven to the two hundred twenty-second reduces to seven squared modulo eleven, which is five.

Maria
Fermat’s theorem gives a one-way primality test. If n is prime, then two to the power n minus one is congruent to one modulo n. But a composite number may pass anyway; three hundred forty-one is eleven times thirty-one, yet it passes the test for base two. Such a composite is called a pseudoprime to that base.

Corey
If the test fails, we know the number is composite. If it passes, the number might be prime or might be a pseudoprime. Testing several bases makes a composite harder to fool, and pseudoprimes are rare compared with primes in the range described in the chapter.

Maria
A primitive root modulo a prime p is a number whose successive powers reach every nonzero remainder before repeating. Two is a primitive root modulo eleven: its powers visit all ten nonzero values. Three is not; its powers return to one after only five steps and miss half the values. Every prime has at least one primitive root.

Corey
The reverse question gives us a discrete logarithm: for a primitive root r, find the exponent e such that r to the e is congruent to a modulo p. With base two modulo eleven, the discrete logarithm of three is eight, because two to the eighth is three.

Maria
Computing a power modulo a large number is fast, but reversing that process to find the exponent is hard for an ordinary computer when the numbers are large. That gap between an easy forward calculation and a difficult reverse calculation is important in cryptography. The chapter notes that a sufficiently large quantum computer could change the picture.

Corey
Congruences also have everyday computing applications. A hash function can map a key k to a memory location using k modulo m. This squeezes a large set of possible keys into locations zero through m minus one, but different keys can land in the same location, causing a collision.

Maria
Collisions are unavoidable when there are many more possible keys than storage locations. A simple way to handle one is linear probing: try the original location, then the next one, and keep going modulo the table size so the search wraps around.

Corey
Another application is pseudorandom numbers. A computer follows a fixed recipe, so the numbers are not truly random, but they can look random. In a linear congruential generator, the next value is a times the current value plus an increment c, all modulo m. A seed starts the sequence, and the modulus keeps outputs between zero and m minus one.

Maria
Because there are only m possible outputs, the sequence eventually repeats; once a value repeats, the future sequence repeats too. The number of outputs before repetition is its period, and useful generators aim for a long period. A multiplicative generator has c equal to zero, but a zero seed would then produce zero forever.

Corey
Check digits use modular arithmetic to detect typing errors. An extra digit is chosen so a weighted sum is a multiple of a chosen modulus. If a digit changes, the sum will often no longer satisfy the rule. A check digit can flag an error without identifying the wrong digit or telling us what the correct one should be.

Maria
A Universal Product Code has twelve digits, including its check digit. Multiply digits in odd positions by three, leave digits in even positions unchanged, and add them; the total must be zero modulo ten. The alternating weights also help detect swaps of neighboring digits.

Corey
A ten-digit ISBN uses a different weighted sum: multiply each digit by its position, add the terms, and work modulo eleven. The check digit is chosen to make the full sum zero modulo eleven. Since the remainder can be ten, the letter X is used for that check digit.

Maria
The chapter highlights that this ISBN rule detects any single-digit error and any transposition of two digits. The prime modulus eleven is part of why the weighted check is strong: the modular arithmetic prevents a change in one digit from being quietly cancelled by the weight.

Corey
Now for cryptography: encryption hides a message, and decryption recovers it. The Caesar cipher shifts every letter three places forward, wrapping around at the end of the alphabet. Represent A through Z as zero through twenty-five, then encrypt p as p plus three modulo twenty-six; decrypt by subtracting three.

Maria
A shift cipher generalizes Caesar’s idea by using any shift k as the key. Encryption adds k modulo twenty-six, and decryption subtracts k. But there are only twenty-six possible keys, so someone could try them all. The affine cipher broadens the rule to a times p plus b modulo twenty-six, and it works as a one-to-one cipher only when a is relatively prime to twenty-six.

Corey
To decrypt an affine cipher, subtract b and multiply by the inverse of a modulo twenty-six. That inverse exists under exactly the same condition that makes the encryption a bijection. In other words, each ciphertext letter must come from exactly one plaintext letter.

Maria
Simple substitution ciphers are vulnerable to letter-frequency analysis. English uses E especially often, followed by letters such as T, A, O, I, N, S, H, and R. A shift cipher moves the whole frequency pattern without changing its shape, so guessing which cipher letter represents E can reveal the key.

Corey
A transposition cipher changes the order of letters inside blocks but does not change the letters themselves. Its key is a permutation of positions, and decryption uses the inverse permutation. Because it only rearranges letters, the original single-letter frequency pattern survives.

Maria
More generally, a cryptosystem consists of plaintexts, ciphertexts, a keyspace, encryption functions, and decryption functions. For each key, encrypting a plaintext and then applying the matching decryption must return exactly the original plaintext. Shift ciphers fit this framework, but their small keyspace makes them weak.

Corey
Traditional ciphers are private-key systems: both people must share and protect the same secret. Public-key cryptography solves the key-sharing problem by separating the keys. The encryption key can be public so anyone can send a protected message, while only the receiver has the private decryption key.

Maria
RSA is a well-known public-key system, named for Rivest, Shamir, and Adleman. Its public key is n and e. To create n, choose two different large primes p and q and multiply them. Choose e relatively prime to the product of p minus one and q minus one; that condition ensures the needed inverse exists.

Corey
To encrypt, encode the message as numbers, split it into blocks smaller than n, and transform each block M into C equal to M to the power e modulo n. Repeated squaring makes the modular exponentiation practical. RSA’s security relies on the difficulty of factoring a very large n back into its prime factors—difficulty as far as current methods are concerned, not a proven impossibility.

Maria
To decrypt, find d, the inverse of e modulo the product of p minus one and q minus one. Then recover each block by computing C to the power d modulo n. Someone who knows p and q can find d; an eavesdropper who only sees n and e would need to factor n to do the same.

Corey
A cryptographic protocol is an exchange of messages designed to achieve a goal. In the Diffie–Hellman key exchange, Alice and Bob publicly agree on a prime p and a primitive root a. Alice privately chooses an exponent, Bob privately chooses another, and they exchange the corresponding powers of a modulo p.

Maria
Each person raises the other’s public value to their own secret exponent. Both arrive at the same shared value, a raised to the product of their secret exponents. A listener sees the exchanged powers but would need to solve a discrete logarithm to recover a secret exponent, which is hard for large parameters by ordinary methods.

Corey
Digital signatures solve a different problem: they prove who sent a message rather than hiding it. In the chapter’s RSA illustration, Alice uses her private key to transform message blocks into a signature. Anyone can apply her public key and check that the original message comes back, so the message is readable but its claimed authorship can be verified.

Maria
There is an important warning: this simple, raw signature method is only a teaching version. An attacker could choose a number as a signature and calculate the corresponding public-key result. Real systems address that weakness by signing a hash of the message instead.

Corey
That brings the chapter full circle. Divisibility led us to remainders, remainders led us to modular arithmetic, and modular arithmetic gave us tools for algorithms, error detection, and secret communication. The same whole-number ideas that begin with asking whether one number divides another help power systems used across the internet.

Ask anything
We've read this whole study set, so questions about it get the best answers.