C ++ Implementation of the big data factorial Problem

Source: Internet
Author: User

First, let's look at a simple N using Recursive Algorithms! Program:

# Include <iostream> using namespace STD; long FAC (INT); int main () {int N; cout <"Enter the number N and output n! : "<Endl; CIN> N; long y = FAC (n); cout <Y <Endl; return 0;} Long FAC (int n) {long F; If (n <0) {cout <"errro, enter a positive number !! "<Endl; Return-1;} else if (n = 0) return 1; else if (n = 1) return 1; F = N * FAC (n-1); Return F ;}

Obviously, N in this program has an upper limit. When long occupies 8 bytes, the value range of F is-9223372036854775808 ~ 9223372036854775807;

So such as computing 1000! The value cannot be solved using the above program.

Of course,

Because of the limited number of digits, no programming language is available, such as 1000! The amount of the multiplication result. The solution is to use Arrays for storage.

First, set the value of the last digit of the array to 1 and the number of digits to 1. Then, store the product of each multiplication back to the array and process the number of more than 10 in each array cyclically, if the value exceeds 10, carry is required. Add 1 to the number of digits. Divide the original number by 10. Store the value of the previous digit in the array of the previous digit, save the remainder to the array of the original digits.

# Include <iostream> using namespace STD; int main () {int array_num [3000]; // int total, Rem = 0, Count, IX if appropriate; // REM is used to save the remainder for (IX = 0; ix <3000; ix ++) array_num [ix] = 0; ix = 2999; array_num [2999] = 1; for (COUNT = 2; count <= 100; count ++) {While (IX> 0) {Total = array_num [ix] * count + REM; REM = 0; if (total> 9) {array_num [ix] = Total % 10; REM = total/10;} else array_num [ix] = total; ix --;} REM = 0; total = 0; ix = 2999;} For (IX = 0; ix <3000; ix ++) {if ( Rray_num [ix]! = 0 | COUNT = 1) {cout <array_num [ix]; Count = 1 ;}}}

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.