题目传送门: https://www.51nod.com/onlineJudge/submitList.html#!userId=11254&problemId=1130
给一个数N,求出N的阶乘的长度
一、取对数的做法
用对数的性质,将若干个数相乘改为若干对数相加的形式O(n)的时间复杂度
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <string>
#include <cmath>
#define ll long long
#define mem(name,value) memset(name,value,sizeof(name))
using namespace std;
const int maxn = 1000005;
const int _max = 1000000;
int a[maxn];
int main()
{
double n;
cin >> n;
double cnt = 0;
for(double i=1;i<=n;i++){
cnt += log10(i);
}
cout << (int)cnt + 1 <<endl;
return 0;
}
二、斯特林公式
ans = 0.5 * log10(2.0 * PI * n) + n * log10(n * 1.0 / E) + 1;
o(1)的时间复杂度
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <string>
#include <cmath>
#define ll long long
#define mem(name,value) memset(name,value,sizeof(name))
#define mod 1000000007
#define PI 3.1415926
#define E 2.718281828459
using namespace std;
const int maxn = 1005;
double getlg(double x){
double cnt = 0;
while(x > 10){
x /= 10;
cnt++;
}
x += cnt;
return x;
}
int main() {
int t;
cin >> t;
for(int i=0;i<t;i++){
int n;
cin >> n;
ll res = 0.5 * log10(2.0 * PI * n) + n * log10(n * 1.0 / E) + 1;
cout << res << endl;
}
return 0;
}