C Exercise Example 25

100 Classic C Examples

Title:Find1 + 2! + 3! + ... + 20!The sum.

Program analysis:This program merely changes accumulation into multiplication.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> // Function to calculate factorial unsigned long long factorial(int n) { unsigned long long result = 1; for(int i = 1; i <= n; i++) { result *= i; } return result; } int main() { unsigned long long sum = 0; // Calculate 1 + 2! + 3! + ... + 20! for(int i = 1; i <= 20; i++) { sum += factorial(i); } // Output the results printf("The sum of 1 + 2! + 3! + ... + 20! is: %llu\n", sum); return 0; }

The output result of the above example is:

1 + 2! + 3! + ... + 20!的和是: 2561327494111820313

Code explanation

  • Header file: Include the necessary header files.stdio.h。
  • Factorial function: unsigned long long factorial(int n)The function is used to calculate a given integer'snfactorial, and the return type isunsigned long longto handle larger values.
    • Initializeresultis 1.
    • UsageforThe loop multiplies from 1 ton。
  • main function:
    • definitionsumVariable to accumulate the sum of all factorials, of typeunsigned long longto handle larger values.
    • UsageforLoop calculates factorials from 1 to 20 and accumulates the results tosum。
    • UsageprintfThe function outputs the final result.

100 Classic C Examples

other extensions