C ++ computing big data class

Source: Internet
Author: User

This was a problem with the teacher when I was in college.

In C ++, it is impossible to accurately calculate the factorial of more than 20 using common data types. In the following example, we use an array to implement any factorial of less than 500. If we calculate a larger number, we can also implement it, but it takes a little longer.

// The following is the program code
# Include <iostream>

Using namespace STD;

Const int max = 10000;

Template <class typename>
Class fact
{
Public:
FACT (typename F): Value (f)
{
For (INT I = 0; I <Max; I ++)
{
Arr [I] = 0;
}
Arr [MAX-1] = 1;
}
// Calculate the factorial
Void calc ()
{
Int I = 0;
Int J = 0;
For (I = 1; I <= value; I ++)
{
// Calculate the factorial
For (j = MAX-1; j> = gettop (); j --)
{
Arr [J] * = I;
}
// Separate the data so that each data has only one digit
For (Int J = MAX-1; j> = gettop (); j --)
{
Arr [J-1] + = arr [J]/10;
Arr [J] = arr [J] % 10;
}
}
}
// Print the result
Void print ()
{
For (INT I = gettop (); I <Max; I ++)
{
Cout <arr [I];
}
Cout <Endl;
}
// Return to the top of the current data
Int gettop ()
{
Int nstart = max;
For (INT I = 0; I <Max; I ++)
{
If (ARR [I]> 0)
{
Nstart = I;
Break;
}
}
Return nstart;
}
PRIVATE:
Typename arr [Max];
Typename value;
};

Int main ()
{
Fact <int> F (100 );
F. Calc ();
F. Print ();
System ("pause ");
Return 0;
}

Related Article

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.