|
发表于 2006-6-24 02:50:02
|
显示全部楼层
10=2*5
由于2的出现次数绝对比5多, 因此只要考查尾数为5及0的数, 计算它们的因子中5的数量
因此写出了如下的代码- #include <stdio.h>
- int main(void)
- {
- unsigned long int N = 123454321;
- printf("%d! has ", N);
- unsigned long int n = 0;
- unsigned long int i = 0;
- while (N > 5) {
- n += N /= 5;
- }
- printf("%d zero at tail\n", n);
- return 0;
- }
复制代码 它的计算时间- rf@RemoteFish:~/src/t$ time ./a.out
- 123454321! has 30863575 zero at tail
- real 0m0.002s
- user 0m0.001s
- sys 0m0.001s
复制代码 但是它还不能回答楼主的问题, 因为它不能处理 "大数", 因此又改出了下面的版本, 利用字符串进行计算- #include <stdio.h>
- #include <string.h>
- /*
- * s / 5
- * 如果结果位数减 1 则返回 1, 否则返回 0
- */
- int div(char s[], int n)
- {
- int i = 0;
- int mod = 0;
- for (i = n - 1; i >= 0; i--) {
- int t = s[i] + 10 * mod;
- s[i] = t / 5;
- mod = t % 5;
- }
- return s[n - 1] == 0;
- }
- /* d = d + s */
- int add(char d[], int nd, char s[], int ns)
- {
- int n = (nd < ns) ? nd : ns;
- int i;
- int x = 0;
- for (i = 0; i < n; i++) {
- d[i] = d[i] + s[i] + x;
- if (d[i] >= 10) {
- d[i] -= 10;
- x = 1;
- } else x = 0;
- }
- if (nd > ns) {
- while (1) {
- d[i] = d[i] + x;
- if (d[i] >= 10) d[i] -= 10;
- else break;
- i++;
- }
- if (i < nd) i = nd;
- } else {
- for ( ; i < ns; i++) {
- d[i] = s[i] + x;
- if (d[i] >= 10) d[i] -= 10;
- else break;
- }
- for ( ; i < ns; i++) {
- d[i] = s[i];
- }
- }
- return i;
- }
- int main(void)
- {
- char buf[800] = "";
- char * src = buf;
- char res[100] = "";
- int src_len = 0;
- int res_len = 0;
- int i;
- memset(res, 0, sizeof(res));
- printf("input the number: ");
- scanf("%s", src);
- src_len = strlen(src);
- for (i = 0; i < (src_len + 1) / 2; i++) {
- int t = src[i] - '0';
- src[i] = src[src_len - i - 1] - '0';
- src[src_len - i - 1] = t;
- }
- while ((src_len -= div(src, src_len)) > 0) {
- res_len = add(res, res_len, src, src_len);
- }
- for (i = res_len - 1; i >= 0; i--) {
- printf("%d", res[i]);
- }
- printf("\n");
- return 0;
- }
复制代码 它的计算时间- rf@RemoteFish:~/src/t$ time ./a.out
- input the number: 12345678987654321
- 3086419746913569
- real 0m7.257s
- user 0m0.002s
- sys 0m0.000s
复制代码 其中输入数据花了一点时间, 真正的计算时间是 user 部分
写的不好, 大家见笑了 |
|