The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
It is defined as:
n! = n × (n - 1) × (n - 2) × ... × 2 × 1
For example
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- 0! is defined to be 1.
Factorials have important applications in mathematics, combinatorics, and probability theory.
Method 1: Using Factorial() Function
R Programming Language offers a factorial() a function that can compute the factorial of a number without writing the whole code for computing factorial.
Syntax: factorial(x)
Parameters:x: The number whose factorial has to be computed.
Returns: The factorial of the desired number.
Example 1
Output:
24
NaN
1
Example 2
Compute the factorial of multiple values
Output:
1 1 2 6 24
Method 2: Finding Factorial Value Using If Else condition
We can create a program to find the factorial of a given number using R if-else conditions.
Steps:
- readline(prompt="Enter a number: ") reads a line of text from the user and displays the prompt "Enter a number: ".
- as.integer() is used to convert the user's input to an integer and store it in the variable num.
- The initial factorial is initialized to 1.
- if-else structure to check the value of num
- If num is less than 0 (negative), it prints "Not possible for negative numbers."
- If num is equal to 0, it prints "The factorial of 0 is 1."
- If num is positive (greater than 0), it enters the else block to calculate the factorial.
- Inside the else block, there is a for loop that iterates from 1 to num.
- In each iteration, the factorial is updated by multiplying it by the current value of i. This loop calculates the factorial of the positive number.
- After the loop completes, it prints the result using print() and paste() functions, displaying the calculated factorial along with a message.
Output:
[1] "The factorial of 6 is 720"