Define a function Z(n, k), Z(n, k) is the factor count of k exist in n!.
For example, Z(4, 2) = 3, as there are three factors of 2 in 4!.
In a naive calculation, the time complexity to calculate Z(n, k) is O(nlogn).
int Z(int n, int k) {
int result = 0;
for (int i = 2; i <= n; ++i) {
int temp = i;
while (temp % k == 0) {
temp /= k;
++result;
}
}
return result;
}
But there is a simple way to generate the result. in 1...n, there are n/k numbers which are dividable by k, there are n/(k^2) numbers which are dividable by k^2, and so on. So we can generate Z(n, k) like below, in O(log(n)) time.
int Z(int n, int k) {
int result = 0;
int temp = k;
while (n / temp >= k) { // Take care temp shouldn't become negative or overflow.
result += n / temp;
temp *= k;
}
result += n / temp;
return result;
}
No comments:
Post a Comment