Factorial Number (n!): Algorithm

Algorithms

Factorial Number

A factorial number is the product of all positive integers up to a given number, denoted by an exclamation mark (!). For example, the factorial of a positive integer n is written as n!, and it is calculated as the product of all positive integers from 1 to n.

The formula for the factorial of a number n is:

n! = n × (n − 1) × (n−2) × … × 3 × 2 × 1

By convention, 0! is defined to be 1.

Note: The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

Here are a few examples:

5! = 5 × 4 × 3 × 2 × 1 = 120

4! = 4 × 3 × 2 × 1 = 24

3! = 3 × 2 × 1 = 6

Here's a simple C program to calculate the factorial of a number using a function:

c Copy Code
#include <stdio.h>

// Function to calculate factorial
int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main() {
    int number;

    // Input from the user
    printf("Enter a positive integer: ");
    scanf("%d", &number);

    // Check for non-negative input
    if (number < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        // Calculate and display the factorial
        printf("Factorial of %d = %d\n", number, factorial(number));
    }

    return 0;
}
Output:
Enter a positive integer: 5
Factorial of 5 = 120

This program defines a function 'factorial' that uses recursion to calculate the factorial of a given number. The 'main' function takes user input, calls the 'factorial' function, and prints the result. Make sure to enter a non-negative integer when prompted.

In summary, factorials are commonly used in mathematics and combinatorics to calculate permutations and combinations, among other things. The concept is also frequently encountered in programming and problem-solving scenarios.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.