Professional Documents
Culture Documents
Primes
Primes
Primality test
Trial Division
bool isPrime(int x) {
for (int d = 2; d * d <= x; d++) {
if (x % d == 0)
return false;
}
return true;
}
There are other ways to test whether a certain number is prime or not.
Such as Miller-Rabin primality test , Fermat primality test etc .
These are not very need at this stage.
Integer factorization
Every number can be factorized into primes.
A number x can be represented as product of prime divisors.
x = p1 ∗ p2 ∗ p3 ∗ ... ∗ pn
example:
36 = 2 ∗ 2 ∗ 3 ∗ 3
Primes 1
vector<long long> trial_division1(long long n) {
vector<long long> factorization;
for (long long d = 2; d * d <= n; d++) {
while (n % d == 0) {
factorization.push_back(d);
n /= d;
}
}
if (n > 1)
factorization.push_back(n);
return factorization;
}
Optimization?
Primes 2
for (long long d : primes) {
if (d * d > n)
break;
while (n % d == 0) {
factorization.push_back(d);
n /= d;
}
}
if (n > 1)
factorization.push_back(n);
return factorization;
}
Problem
https://codeforces.com/contest/1538/problem/D
Sieve
Primes 3
Implementation
#include <bits/stdc++.h>
using namespace std;
vector<int> primes;
void sieve() {
for (int i = 2; i < N; i++) {
if (isPrime[i]) {
primes.push_back(i);
for (int j = i * 2; j < N; j += i) isPrime[j] = false;
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
Complexity
NLogLog(N)
Primes 4
Problem
→ Find the max gcd Pair
Primes 5