-2

I tried using double but it would give me scientific answers like 3.2e+12. I need proper answer. How would I do that??

My code so far:

    int n, x;
    double fact;
    cin>>n;

    while(n--)
    {
        fact=1;
        cin>>x;
        for(;x>1;x--)
            fact*=x;
        cout<<fact<<endl;
    }
user2732146
  • 121
  • 1
  • 8

3 Answers3

1

First things first, using floating point formats such as double and float will always introduce rounding error, if you want to reduce the error with large numbers, use long or long long, however these will not be able to represent values as large as double or long double (note that the behavior and support for long long and long double varies between compilers). You might want to look into BigNums like bigint or bigdouble, though you will sacrifice preformace.

That said, this issue might also be one of setting the formatting: the number is large enough that it is outputted in scientific notation, to change this you can use

cout<<std::fixed;

possible duplicate of How to make C++ cout not use scientific notation

Community
  • 1
  • 1
0

double is a fixed-size type, typically 64 bits, with 53 bits of precision; so it can't accurately represent any integer with more than about 16 digits. The largest standard integer type typically has 64 bits, and can represent integers up to about 19 digits. 100! is much larger than that, so can't be represented accurately by any built-in type.

You'll need a large integer type, representing a number as an array of smaller numbers. There's no standard type; you could use a library like Boost.Multiprecision or GMP or, since this is a programming challenge, implement it yourself. To calculate factorials, you'll need to implement multiplication; the easiest way to do that is with the "long multiplication" algorithm you learnt in school.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

There's no data type can store such a big number as (100!) so far. You should finish something like a BigIntenger class to calculate 100!; And usually,such big number can be stored by strings.

ImaChinese
  • 14
  • 1
  • 7