Lecture 3 Number Theory
Lecture 3 Number Theory
Numbers
Basic Definition of Prime Numbers
Complexity:
Naive Approach
Better Approach
Assume
What’s the upper limit of ?
Better Approach
Proof by contradiction:
Suppose a > √(n), then b >= a > √(n)
=> b > √(n)
=> a*b > √(n)*√(n)= n
=> a*b > n (Contradiction)
Better Approach
Prime Factorization
https://codeforces.com/problemset/problem/129
4/C
Number
Theory and
Modular
Arithmetic
Modular Number System
Mathematically, a number in the decimal number
system can be as large as you want. But computers
(even the most sophisticated ones) have a finite
capability up to which they can process numbers.
121 ≡1 mod 10
Since (121 - 1) = 120 = 10 x 12
Which means 10|120
100 ≡ x mod 7
https://cp-algorithms.com/algebra/module-inverse.html
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
Binary Exponentiation
https://cses.fi/problemset/task/1079
Greatest Common Divisor (GCD)
GCD (42,49) = 7
GCD(0,5) =5
Greatest Common Divisor (GCD)
gcd(a,b) = gcd(a,b-a);
gcd(a,b-a) = gcd(a,b-2*a);
gcd(a,b-2*a) =gcd(a,b-3*a);
……
gcd(a,b-(k-1)*a) = gcd(a,b-k*a)
So gcd(a,b) = gcd(a,b-k*a) =gcd(a,b%a)
Greatest Common Divisor (GCD)
Complexity :
Sieve of Eratosthenes
Suppose, we have to find all prime numbers in the range
?
Naive Approach : Iterate from i =2 to i = N and for each i
calculate whether i is prime or not.
Complexity :
Can we perform better ?
Algorithm
● Complexity :
● Complexity :
So overall complexity:
Algorithm
● Complexity :
https://codeforces.com/contest/1512/problem/G
Resources
● https://usaco.guide/gold/modular
● https://usaco.guide/gold/divisibility
● https://cp-algorithms.com/algebra/primality_tests.html
● https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html
Practice Contest for Number Theory