I am looking for an efficient algorithm to find the number of divisors for all numbers in a huge range up to $10^9$.
Such a task is presented in these two problems: NDIV, and spoj NFACTOR
I used prime factorization to find the number of divisors for each number in the specified range using the following c++ code:
#include <iostream>
using namespace std;
int fact(int x) {
int sum = 0;
for (int i = 0, ln = prime.size(); i < ln && prime[i] * prime[i] <= x;
++i) {
for (sum += (x % prime[i] == 0); x % prime[i] == 0; x /= prime[i])
;
if (sum > 10)
return 11;
}
sum += (x > 1);
return sum;
}
int main() {
// your code goes here
return 0;
}
Where "prime" is an array with all prime numbers up to $10^9$, calculated using Sieve of Eratosthenes algorithm.
Are you familiar with the divisor function? If $n=p^aq^br^c, p,q,r$ prime, the number of factors of $n$ is $(a+1)(b+1)(c+1)$ This works for any number of prime factors.
Now take your $N$ and factor it. You can find the patterns of factors that will work. For example, if $N=8$, you can have numbers of the form $p^7,p^3q,$ or $pqr$. The seventh powers are easy to check. For $p^3q$ I would go through the cubes of primes and for each compute the range of $q$ that works, then compute the number of primes in that range. $pqr$ will be the slow one. We can assume $p \lt q \lt r$ but you still have a double loop over primes before finding the range of $r$ that works.