问题
I m trying to find number of factors of product of big numbers.
The problem statement is this : Suppose you are given N numbers(let say N = 10), each number <= 1000000. How to find the number of factors of the product of such numbers.
Can someone please provide an efficient algorithm for doing this.
Example :
1) N = 3 and Numbers are 3, 5, 7
Ans = 8 (1, 3, 5, 7, 15, 21, 35, 105)
2) N = 2 and Numbers are 5, 5
Ans = 3 (1, 5 and 25)
回答1:
Editorial for the problem is here
http://discuss.codechef.com/questions/15943/numfact-editorial
int total = 0, N = 0, Number;
scanf ("%d", &total);
while (total--)
{
scanf ("%d", &N);
map<int, int> Counter;
for (int i = 0; i < N; i++)
{
scanf ("%d", &Number);
for (int j = 2; j * j <= Number; j++)
{
while (Number % j == 0)
{
Counter[j]++;
Number /= j;
}
}
if (Number > 1) Counter[Number]++;
}
int Answer = 1;
for (map<int, int>::iterator it = Counter.begin(); it != Counter.end(); it++)
Answer *= (it->second + 1);
printf ("%d\n", Answer);
}
This got Accepted.
Sample Inputs and Outputs:
7
3
3 5 7
3
2 4 6
2
5 5
10
2 2 2 2 2 2 2 2 2 2
1
100
10
10000 10000 10000 10000 10000 10000 10000 10000 10000 10000
10
1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000
8
10
3
11
9
1681
3721
回答2:
Factorize each number into list of prime factors and their multiplicities, L(n) = { p_i , k_i }
, for a number n = Π piki. Numer of divisors for such n is ND( L(n) ) = Π (ki+1) a product of all coefficients, each incremented by 1 (this includes 1 and n itself as divisors of n). This corresponds to picking none, one, ... ki of each of them to multiply.
To calculate the ND of a product of arbitrary number of numbers, factorize each and merge their factorizations, where in case of matching primes their coefficients are added together. Then calculate the ND of the merged factorization.
To merge many factorizations together, start by merging two of them; then merge the result and the next one; then merge the last result and the next factorization, and so on. This is called folding. Or better merge them pairwise, then merge the results in same pairwise fashion, and so on util only one merged result is left. That's similar to how a bottom-up mergesort is done.
回答3:
Multiply all the numbers, factorize the result, count all divisors:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int p = 1;
for (int i = 1; i < argc; i++)
p *= strtol(argv[i], NULL, 10);
int n = 0;
int s = sqrt(p) + 1;
for (int i = 1; i <= s; i++)
if (p % i == 0)
n += 2 - (p / i == i); // obfuscation ;)
printf("%d\n", n);
return 0;
}
来源:https://stackoverflow.com/questions/17388543/how-to-find-number-of-factors-of-product-of-numbers