Factorial - Array - C++

a 夏天 提交于 2019-12-12 02:27:24

问题


The problem is to compute factorial of a number. I've debugged my code, and it works fine for any input and produces correct output for all the given test cases. But still, I'm getting Wrong Answer on SPOJ.

Problem:

An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.

Any insight would be helpful. Am I missing some critical test cases?

My Code:

#include <iostream>
using namespace std;
int main()
{

long T;
cin>>T;
while(T--)
{
    long long N;

    long long index, count;
    cin>>N;
    long long a[300];
    long long i=1;
    a[0]=1; count=1;
    while(i<=N)
    {

        long long z=0;
        long long k; long long x;
        long long j=i;
        long long temp=0; long long current=0;
        for(k=0; k<count;k++)
        {
            x=(a[k]*j)+temp;
            a[k]=x%10;
            temp=x/10;
        }
        if(temp>0)
            while(temp>0)
            {
                a[k]=temp;
                temp=temp/10;
                k++;
                count++;
            }


        i++;
    }


    for(long long g=count-1; g>=0; g--)
        cout<<a[g];
        cout<<"\n";

}
return 0;
}

回答1:


This line:

a[k]=temp;

should be:

a[k]=temp % 10;



回答2:


Try this out

#include <iostream>

long double factorial(int n)
{
    long double r = 1;

    while(n > 1){
        r *= n;
        --n;
    }

    return r;
}

int main()
{
    std::cout << factorial(100) << std::endl;

    system("PAUSE");
}


来源:https://stackoverflow.com/questions/23874020/factorial-array-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!