HDOJ 1018(數論)

題意描述

Problem Description
In many applications very large integers numbers are required. Some of these applications are using keys for secure transmission of data, encryption, etc. In this problem you are given a number, you have to determine the number of digits in the factorial of the number.

Input
Input consists of several lines of integer numbers. The first line contains an integer n, which is the number of cases to be tested, followed by n lines, one integer 1 ≤ n ≤ 107 on each line.

Output
The output contains the number of digits in the factorial of the integers appearing in the input.

Sample Input
2
10
20

Sample Output
7
19

思路

剛看到題的一瞬間,果斷寫了個高精度交了上去,TLE了,再看數據範圍,嚯!1e7,然後就去翻了題解,發現是數論問題,求階乘位數有兩種方法:

1.10m<n!<10(m+1) 若求得M,則M+1爲答案。對方程兩邊以10爲底求對數,得M<log10(n!)<M+1,通過循環求值即可
2.斯特林公式:n! ≈ sqrt(2* n * pi)* (n/e)^n,則 M+1=(int)(0.5 * log(2.0 * n *PI)+n * log(n)-n)/(log(10.0)) )+1;

AC代碼

方法1 複雜度O(n):

#include<vector>
#include<iostream>
#include<cstring> 
#include<queue>
#include<set>
#include<cmath>
#include<algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0); 
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int N=15;
const int INF=0x3f3f3f3f;
int main() {
	IOS;
	int T;
	cin>>T;
	while(T--){
		int n;
		cin>>n;
		double ans=0;
		for(int i=1;i<=n;i++){
			ans+=log(i)/log(10);
		}
		cout<<(int)ans+1<<endl;
	}
    return 0;
}

方法2 複雜度O(1):

#include<vector>
#include<iostream>
#include<cstring> 
#include<queue>
#include<set>
#include<cmath>
#include<algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0); 
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int N=15;
const double PI=3.1415926;
const int INF=0x3f3f3f3f;
int main() {
	IOS;
	int T;
	cin>>T;
	while(T--){
		int n;
		cin>>n;
		double ans=0;
		cout<<(int)((0.5*log(2.0*n*PI)+n*log(n)-n)/(log(10.0)))+1<<endl;
	}
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章