Time Limit: 2s Memory Limit: 192MB
Problem Description
Write a program to calculate the value of 1977!
Input Format
None
Output Format
None
Sample Input
None
Sample Output
None
Code
#include <iostream>
using namespace std;
const int MAX_DIGITS = 10000; // Estimate the number of digits in 1977!
void factorial(int n) {
int result[MAX_DIGITS] = {0};
result[0] = 1;
int digits = 1; // Current number of digits in the result
for (int i = 2; i <= n; i++) {
int carry = 0;
for (int j = 0; j < digits; j++) {
int product = result[j] * i + carry;
result[j] = product % 10;
carry = product / 10;
}
while (carry > 0) {
result[digits] = carry % 10;
carry /= 10;
digits++;
}
}
// Output result
for (int i = digits - 1; i >= 0; i--) {
cout << result[i];
}
cout << endl;
}
int main() {
factorial(1977);
return 0;
}
Output Result

Methodology
-
Large Number Representation: Use an array to store large numbers, with each element representing a digit.
-
Multiplication Operation: Multiply from 1 up to 1977, simulating manual multiplication.
-
Carry Handling: Handle carry after each multiplication.
-
Output Result: Output the result starting from the highest digit.
Code Explanation
-
Array Initialization: The
<span>result</span>array is used to store large numbers, initialized to 1 (0! = 1). -
Factorial Calculation:
-
Outer loop: Multiply from 2 to 1977
-
Inner loop: Multiply each digit of the current result array by the multiplier, adding the carry
-
Handle carry: Distribute the carry to higher digits
Output Result: Output the digits from the highest position in the array.
Considerations
-
The result of 1977! is extremely large, with over 5000 digits
-
Use an array to simulate manual multiplication to ensure accurate calculations
-
The code allocates an array space of 10000 digits, sufficient to store the result of 1977!
This method accurately calculates the factorial of 1977 by simulating large number multiplication using an array.

C++ Basic Tutorial Collection
C++ Basic Resources
1. C++ Output
2. C++ Variables
3. C++ Input
4. C++ Expressions
5. IF Statements
6. IF Applications
7. WHILE Loop Statements
8. FOR Loop Statements
9. Arrays
10. One-Dimensional Arrays
11. Two-Dimensional Arrays
12. C++ Functions
13. C++ File Operations – Writing Files
If you find it interesting, please click on me



