DSA · Competitive Programmer · Pattern 1 of 9
Number Theory
14 problems.
Your progress0%
- 1st Visit
- 0/14
- 2nd Visit
- 0/14
- Revise
- 0/14
About this pattern
Number theory problems revolve around divisibility, primes, gcd and lcm, and modular arithmetic. The core tools are the Euclidean algorithm, a sieve of Eratosthenes or a smallest-prime-factor sieve for fast factorisation, Euler's totient function and fast modular exponentiation. Look for statements about divisors, coprimality, multiples inside a range, or huge values that matter only through their prime factors. A frequent trick is to iterate over a divisor or a multiple instead of over pairs of elements, which turns quadratic work into a harmonic sum of order O(M log M). Inclusion-exclusion and binary search on the answer combine well with counting multiples.
long long power(long long b, long long e, long long mod) {
long long r = 1; b %= mod;
while (e > 0) {
if (e & 1) r = r * b % mod;
b = b * b % mod; e >>= 1;
}
return r;
}
// spf[x] = smallest prime factor of x, for 2 <= x <= N
vector<int> buildSpf(int N) {
vector<int> spf(N + 1, 0);
for (int i = 2; i <= N; i++)
if (spf[i] == 0)
for (int j = i; j <= N; j += i)
if (spf[j] == 0) spf[j] = i;
return spf;
}