FCTRL2: Getting Wrong Answer

Please check the following program and find where is it going wrong. I matched the result from online factorial calculators and it is correct.

#include<iostream>
using namespace std;

double fact(int n)
{
     double value=1.0;
     
     if(n==0)
     return(value);
     else
     {
         value=n*fact(n-1);
         return(value);
         }} 
     
int main()
{
    int t,n[100];
    cin>>t;
    double result;
    if(t<=100&&t>=1)
    {
                    for(int i=0;i<t;i++)
                    {
                            cin>>n[i];
                            }}
     cout<<endl;                       
    for(int i=0;i<t;i++)
    { 
            result=0.0;     
            if(n[i]>=1&&n[i]<=100)
    {
            result=fact(n[i]);
            cout<<result<<endl;
}
}
return 0;
}

You have to return exact value of n! not some rounded double…

1
11

and output have to be

39916800

your program returns

3.99168e+07

see the values here - http://2000clicks.com/MathHelp/BasicFactorialTable.aspx

1 Like

Ohh. I see the problem now. My prog prints scientific form of the output. How can I get these output in exact value, since there isn’t any datatype in C++ that can store such long numbers?

In C++ you have to implement your own - represent long number as char array and implement multiply operation like:

 1234
 x 56
-----
 7404
6170
=====
69104

in implementation it is easier to use int array and perform modulo 10 operation just once - at the end

    [1][ 2][ 3][ 4]
 x         [ 5][ 6]
-------------------
   [ 6][12][18][24]
[5][10][15][20]
===================
[5][16][27][38][24]
~~~~~~~~~~~~~~~~~~~
 6   9   1   0   4

Sorry, but I am a beginner. Couldn’t understand what you mean. I understand that I should store each separate digit in successive elements of an integer array. But again I am stuck, how can I do this?