Normal integer data types can't store the result of large factorials, we need to use an array to represent the digits individually to perform a digit-by-digit multiplication. When multiplying with the next number in the factorial calculation, multiply each digit of the current result with the new number, handling carries appropriately. Algorithm outline:
Initialize:
Loop through numbers to multiply:
def factorial(n):
result = [1]
for i in range(2, n + 1):
carry = 0
for j in range(len(result)):
temp = result[j] * i + carry
result[j] = temp % 10
carry = temp // 10
while carry > 0:
result.append(carry % 10)
carry //= 10
return result
n = 50
print(''.join([str(x) for x in factorial(n)[::-1]]))
const n = 50;
function factorial(n) {
const result = [1];
for (let i = 2; i <= n; i++) {
let carry = 0;
for (let j = 0; j < result.length; j++) {
let temp = result[j] * i + carry;
result[j] = temp % 10;
carry = Math.floor(temp / 10);
}
while (carry > 0) {
result.push(carry % 10);
carry = Math.floor(carry / 10);
}
}
return result.reverse().join("");
}
console.log(factorial(n));