fork download
  1. #include <stdio.h>
  2.  
  3. #define MAX_DIGITS 200 // Enough space for 50!
  4.  
  5. // Multiplies the big number (stored in result as digits in reverse order)
  6. // by the given factor. The current size of the number is pointed to by result_size.
  7. void multiply(int factor, int result[], int *result_size) {
  8. int carry = 0;
  9. for (int i = 0; i < *result_size; i++) {
  10. int prod = result[i] * factor + carry;
  11. result[i] = prod % 10;
  12. carry = prod / 10;
  13. }
  14. while (carry) {
  15. result[*result_size] = carry % 10;
  16. carry /= 10;
  17. (*result_size)++;
  18. }
  19. }
  20.  
  21. // Computes factorial(n) using an iterative approach.
  22. void factorial(int n) {
  23. // The big number is stored in an array, with the least-significant digit at index 0.
  24. int result[MAX_DIGITS] = {0};
  25. int result_size = 1;
  26. result[0] = 1; // Initialize with 1
  27.  
  28. for (int i = 2; i <= n; i++) {
  29. multiply(i, result, &result_size);
  30. }
  31.  
  32. // Print the big number in the correct order (most-significant digit first)
  33. for (int i = result_size - 1; i >= 0; i--) {
  34. printf("%d", result[i]);
  35. }
  36. printf("\n");
  37. }
  38.  
  39. int main(void) {
  40. factorial(50);
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
30414093201713378043612608166064768844377641568960512000000000000