POJ1423 HDU1018 "Sterling formula" "High precision"

Source: Internet
Author: User

Topic Links:

http://poj.org/problem?id=1423

http://acm.hdu.edu.cn/showproblem.php?pid=1018


Main topic:

Ask n! how many bits there are. 1<=n<=10^7.


Ideas:

N is a large scale. You cannot directly simulate the number of digits to be evaluated. Consider this approach first:

Set a = N! = 1*2*3*4*...*n, then the number of digits is (int) log10 (A) + 1

and (int) log10 (A) = log10 (1*2*3*...*n) = log10 (1) * LOG10 (2) * LOG10 (3) * ... * LOG10 (N)

This adds up to the result. But because N is 10^7 scale, so the accumulation on the HDU can be AC, but

The POJ is still timed out.

It should be done with a sterling formula. Stirling Formula: When N is big enough, n! = (n/e) * N * sqrt (2*pi*n).

log10 (N) + 1 = (int) (LOG10 (2*pi*n)/2 + N*LOG10 (n/e) + 1. the constant e and π are used. To ensure that the fine

degrees, define the constant E = 2.7182818284590452354, define PI = 3.1415926535897932385.


AC Code:

poj1423#include<iostream> #include <algorithm> #include <cstdio> #include <cstring># Include<cmath>using namespace Std;const Double e = 2.7182818284590452354;const double pi = 3.1415926535897932385; Double strling (int N) {    return 0.5*log10 (2*pi*n) + n*log10 (n/e);} int main () {    int t,n;    Cin >> T;    while (t--)    {        cin >> N;        cout << (int) strling (N) +1 << Endl;    }    return 0;}

hdu1018# include<stdio.h># Include<math.h>int Main () {    int n,m,i;    Double sum;    scanf ("%d", &n);    while (n--)    {        scanf ("%d", &m);        sum = 0;        for (i=1;i<=m;i++)            sum + = (log10 (i));        printf ("%d\n", (int) sum+1);    }        return 0;}


POJ1423 HDU1018 "Sterling formula" "High precision"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.