gpt4 book ai didi

c - 查找大阶乘中特定数字的计数

转载 作者:行者123 更新时间:2023-12-05 06:07:34 25 4
gpt4 key购买 nike

我需要计算一个大的阶乘中特定数字(0 和 9 之间)的计数

#include <stdio.h>
int main()
{
unsigned long long int x;
int n , count = 0;
scanf("%llu %d", &x , &n);
int i = x - 1;
while(i > 1)
{
x *= i;
i--;
}
while (x>0)
{
if(x%10 == n) count++;
x /= 10;
}
printf("%d",count);
return 0;
}

这对小数字很有效
输入:7 0
输出:2
描述: 7! = 5040 其中有两个零
但是对于大数需要很长时间
输入:50 2
输出:溢出和时间限制!

有什么想法可以在时间方面优化这个程序吗?例如,一种无需计算阶乘即可计算位数的数学方法

最佳答案

终于找到了我的答案,这可能对其他人有帮助。

这个想法正在使用 big numbers multiplication :

#include<stdio.h>

int main()
{
int n , p;
scanf("%d %d" , &n , &p);
int digits[1000] = {1};
for(int i = 2 ; i <= n ; i++)
{
for(int k = 0 ; k < 1000 ; k++) digits[k] *= i;
for(int k = 0 ; k < 1000 ; k++) if(digits[k] > 9)
{
digits[k+1] += digits[k]/10;
digits[k] %= 10;
}
}
int a , count = 0;
for(a = 999 ; !digits[a] ; a--);
a++;
for (int j = 0;j<a;j++) if(digits[j] == p) count++;
printf("%d" , count);
}

关于c - 查找大阶乘中特定数字的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65396240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com