我有以下问题,如标题中所述:对于N的每个值,打印出N中有多少位数。例如,如果n = 32000,我应该得到130271。 我想过一个递归的解决方案。它适用于较小的数字,但对于上面的例子,它打印31997.我确信我的想法是错误的,但我无法找到更大数字的规则。在某处,n!我想,我开始跳过步骤。我的意思是,它不会随着数字增加,而是增加两个或三个。 我有以下代码:
#include <stdio.h>
#include <stdlib.h>
//For each value of N, print out how many digits are in N!.
int how_many(int n){
if( n <= 3)
return 1;
if( n == 4)
return 2;
if( n == 5 || n == 6)
return 3;
if( n >= 7)
return 1 + how_many(n-1);
}
int main()
{
int n;
printf("The number n is : ");
scanf("%d", &n);
int counter = 0;
counter = how_many(n);
printf("n! has %d digits", counter);
return 0;
}
答案 0 :(得分:7)
你正在做的事情log10(N!)
。一旦你意识到这一点,你可以使用斯特林的近似或这里探讨的其他技术之一:https://math.stackexchange.com/questions/138194/approximating-log-of-factorial
答案 1 :(得分:1)
@JohnZwinck的答案解决了我的问题。以下是生成的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define M_PI 3.14159265358979323846
//For each value of N, print out how many digits are in N!.
int digits_in_factorial(int n){
return floor((n+0.5)*log(n) - n+ 0.5*log(2*M_PI))/log(10) + 1;
}
int main()
{
int n;
printf("Numarul n este : ");
scanf("%d", &n);
int counter = 0;
counter = digits_in_factorial(n);
printf("n! are %d cifre", counter);
return 0;
}
答案 2 :(得分:0)
return 1 + how_many(n-1);
应该更像
return log10(n) + how_many(n-1);
使用OP的原始整数方法且低于how_many(32000) --> n! has 123560 digits
- 更好的估算。
int how_many(int n) {
if (n <= 3)
return 1;
if (n == 4)
return 2;
if (n == 5 || n == 6)
return 3;
int count = 0 + how_many(n - 1);
while (n > 3) {
n /= 10;
count++;
}
return count;
}
IAC,OP has found斯特林的方法。