HDU_1018
题目链接
- 点此跳转
方法1
∵ n ! = 1 × 2 × . . . × n \because n!=1\times2\times...\times n ∵n!=1×2×...×n
∴ n \therefore n ∴n 的位数
= ⌈ l g ( n ! ) ⌉ = \left\lceil lg(n!) \right\rceil =⌈lg(n!)⌉
= ⌈ l g ( 1 × 2 × . . . × n ) ⌉ = \left\lceil lg(1\times2\times...\times n) \right\rceil =⌈lg(1×2×...×n)⌉
= ⌈ l g ( 1 ) + l g ( 2 ) + . . . + l g ( n ) ⌉ =\left\lceil lg(1)+lg(2)+...+lg(n)\right\rceil =⌈lg(1)+lg(2)+...+lg(n)⌉
注:
- l g ( x ) = l o g 10 x lg(x)=log_{10}x lg(x)=log10x
- ⌈ ⌉ \left\lceil \right\rceil ⌈⌉ 表示向上取整
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#define LL long long
#define mem(a, b) memset(a, b, sizeof a)
#define lowbit(x) (-x&x)
#define IOS ios::sync_with_stdio(false),cin.tie(0)
#define endl '\n'
#define rev(x) reverse(x.begin(), x.end())
#define INF 0x3f3f3f3f
using namespace std;
double ans;
int n;
void solve() {
int tt;
cin >> tt;
// tt = 1;
while (tt -- ) {
cin >> n;
ans = 0;
for (int i = 1; i <= n; i ++ ) ans += log10(i);
printf("%d\n", (int)(ans + 1));
}
}
int main() {
IOS;
solve();
return 0;
}
方法二
利用斯特林公式( S t i r l i n g ′ s a p p r o x i m a t i o n Stirling's \ approximation Stirling′s approximation)。
∵ n ! ≈ 2 π n ( n e ) n \because n! \approx \sqrt{2 \pi n}{(\frac{n}{e})}^n ∵n!≈2πn(en)n
∴ n \therefore \ n ∴ n 的位数
= ⌈ l g ( n ! ) ⌉ = \left \lceil lg(n!) \right \rceil =⌈lg(n!)⌉
= ⌈ 1 2 l g ( 2 π n ) + n l g ( n e ) ⌉ = \left \lceil \frac{1}{2}lg(2 \pi n) + nlg({\frac{n}{e}}) \right \rceil =⌈21lg(2πn)+nlg(en)⌉
= ⌈ 1 2 l n ( 2 π n ) + n l n ( n e ) l n ( 10 ) ⌉ = \Large\left \lceil \frac{\frac{1}{2}ln(2 \pi n) + nln({\frac{n}{e}})}{ln(10)} \right \rceil =⌈ln(10)21ln(2πn)+nln(en)⌉
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#define LL long long
#define mem(a, b) memset(a, b, sizeof a)
#define lowbit(x) (-x&x)
#define IOS ios::sync_with_stdio(false),cin.tie(0)
#define endl '\n'
#define rev(x) reverse(x.begin(), x.end())
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
double ans;
int n;
void solve() {
int tt;
cin >> tt;
// tt = 1;
while (tt -- ) {
cin >> n;
ans = ceil((0.5 * log(2 * PI * n) + n * log(n) - n) / log(10));
printf("%d\n", (int)ans);
}
}
int main() {
IOS;
solve();
return 0;
}