Home >Backend Development >C++ >How Can We Calculate the Factorial of Arbitrarily Large Numbers and Display All Digits Without External Libraries?
Calculating the Factorial of Arbitrarily Large Numbers with All Digits Shown
Calculating the factorial of arbitrarily large numbers is a classic algorithm problem. However, it poses a unique challenge if we require all the digits of the answer without relying on external libraries. This article delves into a method that effectively addresses this challenge.
The Proposed Solution
The solution revolves around using an array of integers to represent the factorial and performing multiplication as we would when solving manually. Let's examine the code that implements this approach:
int max = 5000; // Display the factorial void display(int arr[]) { int ctr = 0; for (int i = 0; i < max; i++) { if (!ctr && arr[i]) ctr = 1; if (ctr) std::cout << arr[i]; } } // Calculate the factorial void factorial(int arr[], int n) { if (!n) return; int carry = 0; for (int i = max - 1; i >= 0; --i) { arr[i] = (arr[i] * n) + carry; carry = arr[i] / 10; arr[i] %= 10; } factorial(arr, n - 1); } int main() { int *arr = new int[max]; std::memset(arr, 0, max * sizeof(int)); arr[max - 1] = 1; int num; std::cout << "Enter the number: "; std::cin >> num; std::cout << "factorial of " << num << "is :\n"; factorial(arr, num); display(arr); delete[] arr; return 0; }
Explanation
This solution provides a comprehensive approach to calculating the factorial of large numbers without using external libraries, ensuring all digits of the result are shown.
The above is the detailed content of How Can We Calculate the Factorial of Arbitrarily Large Numbers and Display All Digits Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!