Number Of Divisors
Question 1
Question
Given , find number of divisors of .
Resources
- Codeforces Tutorial: https://codeforces.com/blog/entry/22317
- Codeforces Gym: https://codeforces.com/gym/100753 ➝ Problem K
- SPOJ: https://www.spoj.com/problems/NUMDIV/
Naive Solution
The complexity of the following is .
Naive Solution
void solve() {
int n; cin >> n;
int an = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
an += 2;
if (i * i == n) --an;
}
}
cout << an << '\n';
}
solution
- Let's split where contains only prime factors in range and rest of primes in .
- Let denote our answer. Now, since and are coprime, .
- can be calculated directly similar to naive solution in .
- Observe that falls into one of these cases:
- is prime
- is square of prime
- is product of two distinct primes
- This is because there can be at max only two divisors of , otherwise one of them surely must be .
//pseudocode -- will update later
void solve() {
int n; cin >> n;
vector<int> pr; // all primes till 10^6
int an = 1;
for (auto &p : pr) {
if (p * p * p > n) break;
int cn = 1;
while (n % p == 0) { n /= p; ++cn; }
an *= cn;
}
// use miller-rabin
if (n is prime) { an *= 2; }
else if (n is square of prime) { an *= 3; }
else an *= 4;
cout << an << '\n';
}