前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HDOJ 1018(数论)

HDOJ 1018(数论)

作者头像
dejavu1zz
发布2020-10-23 15:16:26
3240
发布2020-10-23 15:16:26
举报
文章被收录于专栏:奇妙的算法世界

题意描述

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):

代码语言:javascript
复制
#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):

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/03/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意描述
  • 思路
  • AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档