http://acm.hdu.edu.cn/showproblem.php?pid=1018
题意:求一个数阶乘的位数。
思路:求一个数的位数,普通的for对这么大的数先求出来是不现实的,所以就有了下面的公式:
n的位数 = (int)log10(n)+1。
那n!的位数就是(int)log10(1)+(int)log10(2)+(int)log10(3)+...+(int)log10(n)+1。
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;
typedef long long ll;
const int N = 2003;
int main()
{
// freopen("in.txt", "r", stdin);
int t, x;
scanf("%d", &t);
while(t--)
{
scanf("%d", &x);
double sum = 0;
for(int i = 1; i <= x; i++)
sum+=log10(i);
printf("%d\n", (int)sum+1);
}
return 0;
}
斯特林公式:n! = sqrt(2πn)*(n/e)^n。
换成以10为底的对数就是:
log10(n!) = 0.5*log10(2πn)+n*log10(n)-n*log10(e)。
注意下π和e的值,输出记得转化成int。
很简单的,自己动手算算就行。
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;
typedef long long ll;
const int N = 2003;
const double PI = 3.1415926535897932385;
const double e = 2.7182818284590452354;
int main()
{
// freopen("in.txt", "r", stdin);
int t, n;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
double sum = 0;
sum = 0.5*log10(2*PI*n)+n*log10(n)-n*log10(e);
printf("%d\n", (int)sum+1);
}
return 0;
}