C Language Cumulative Product Algorithm and Factorial Algorithm, and Their Differences

C Language Cumulative Product Algorithm and Factorial Algorithm, and Their DifferencesCumulative Product AlgorithmThe cumulative product algorithm in C language, as the name suggests, is the product obtained by multiplying a set of data together, such as a*b*c*d*e.The cumulative product algorithm is one of the basic algorithms in C language, commonly used to calculate the product of all elements in an array (for example, in statistics for grade calculations) and so on.Implementation of Cumulative Product AlgorithmThe cumulative product algorithm in C can be implemented using either loops or recursion. Please refer to the example code below.Example Code for Cumulative Product Algorithm ImplementationHere, we temporarily use a for loop; the recursive method will be used when introducing the factorial algorithm below.

#include <stdio.h>// for loop, considering overflow, return type declared as long long
long long productArray_for(int arr[], int size){
    long long productResult = 1;
    for (int i = 0; i < size; i++) {
        productResult *= arr[i];
    }
    return productResult;
}
int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int productResult = productArray_for(numbers, size);
    printf("for loop calculated total product of array elements: %d\n", productResult);
    return 0;
}

The code compiles and runs, producing the output:

for loop calculated total product of array elements: 120

Factorial AlgorithmAccording to the materials I have collected and read, the factorial algorithm is also one of the cumulative product algorithms in C language, but in mathematical definitions, factorial is generally applied to positive integers and satisfies the formula:n!=n·(n-1)!Implementation of Factorial AlgorithmThe factorial algorithm is generally implemented using recursion; please refer to the example code below.

#include <stdio.h>// Factorial function
// Since factorial is generally applied to positive integers, consider overflow, thus using unsigned long long to represent the factorial result.
unsigned long long factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}
int main() {
    int numbers = 5;
    int productResult = factorial(numbers);
    printf("Using recursion, the factorial of 5 is: %llu\n", productResult);
    return 0;
}

The code compiles and runs, producing the output:

Using recursion, the factorial of 5 is: 120

Disclaimer: The content is for reference only, does not guarantee correctness, and should not be used as the basis for any decisions!

Leave a Comment