Home >Backend Development >C++ >How Can We Calculate the Factorial of Arbitrarily Large Numbers and Display All Digits Without External Libraries?

How Can We Calculate the Factorial of Arbitrarily Large Numbers and Display All Digits Without External Libraries?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 12:15:13873browse

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

  • The arr array represents the factorial.
  • factorial() progressively multiplies the factorial by the current number.
  • display() ensures leading zeros are omitted.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn