Number Theory
Number Theory
- Srivaths P
Goal:
To learn:
• Basic Primality Testing
• Sieve of Eratosthenes
• Prime Factorization
• Basic Modular Arithmetic
Primality Testing
A primality test is an algorithm for determining whether a number is
prime or composite.
Therefore, if the number is not a prime, it must have atleast one factor
less than or equal to the square root of the number.
Sieve of Eratosthenes
Sieve of Eratosthenes can find all the prime numbers upto a given limit
in 𝑂(𝑁 log log 𝑁) time complexity.
Any composite number 𝐶 must have a prime factor 𝑃 such that 𝑃 < 𝐶.
We will repeatedly find the first number that does not have any prime
factors, as that number must be prime. Then we will mark the multiples
of the number as composite.
Sieve of Eratosthenes – Code
void sieve(int n) {
bool primes[n+1];
fill(primes, primes+n+1, true);
1 1 1 1
+ + + +⋯
2 3 5 7
The above sum comes out as log log 𝑁 when the primes are less than 𝑁.
We will use the fact that the smallest divisor of any number 𝑁 is prime,
and it will be less than 𝑁.
𝑞 𝑞 𝑞 𝑞
𝑁 can be represented as 𝑝0 0 ∗ 𝑝1 1 ∗ 𝑝2 2 ∗ ⋯ ∗ 𝑝𝑘 𝑘 where 𝑝𝑖 is prime.
Let us assume that the prime array is sorted.
if (n > 1)
facts.push_back(n);
return facts;
}
Modular Arithmetic
Modular Arithmetic is arithmetic operations involving taking the
modulo with some modulus. It is usually given in problem statements
so that the solution doesn’t overflow in case the answer is huge.
Modular multiplication:
𝐴 ∗ 𝐵 % 𝑀 = (𝐴 % 𝑀) ∗ (𝐵 % 𝑀) % 𝑀.
Problems
• https://codeforces.com/problemset/problem/472/A
• https://codeforces.com/problemset/problem/1475/A
• https://codeforces.com/problemset/problem/1679/A
• https://codeforces.com/problemset/problem/1165/D
Resources
• https://en.wikipedia.org/wiki/Primality_test
• https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
• https://cp-algorithms.com/algebra/factorization.html (advanced)
• https://bit.ly/3cl0Vdj (modular arithmetic basics)