題目點這:http://uva.onlinejudge.org/external/1/160.pdf
思路:遍曆1~n計算質因子個數即可。
你若還想再快點的話,就用[n/p]+[n/p^2]+[n/p^3]+...+1在O(log n/log p)的時間內統計出n!的質因子p的個數。(不過此題n太小,兩種方法在時間上相差不大)
完整代碼:
/*0.016s*/#include<cstdio>#include<cmath>#include<cstring>int prime[100], c, ans[100];bool vis[110];inline void create_prime(){int i, j;for (i = 2; i <= 11; ++i)if (!vis[i]){prime[c++] = i;for (j = i * i; j < 110; j += i)vis[j] = true;}for (; i < 110; ++i)if (!vis[i])prime[c++] = i;}int main(void){create_prime();int n, temp;while (scanf("%d", &n), n){memset(ans, 0, sizeof(ans));printf("%3d! =", n);for (int i = 2; i <= n; i++){temp = i;for (int j = 0; j < c && prime[j] <= i; j++){while (temp % prime[j] == 0){++ans[prime[j]];temp /= prime[j];}}}for (int i = 0, j = 0; prime[i] <= n; i++, j++){if (j % 15 == 0 && j) printf("\n ");printf("%3d", ans[prime[i]]);}putchar('\n');}return 0;}