Factorial of a number in R Programming Language

Factorial of a number in R Programming Language

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
This example finds the factorial of a number normally. However, you can find it using recursion as well.

Program:
#Only positive numbers(No include 0 and Negative numbers)
num = as.integer(readline(prompt=”Enter a number: “))
factorial = 1
for(i in 1:num)
factorial = factorial * i
print(paste(“The factorial of”, num ,”is”, factorial))

Output:
Enter a number: 9
[1] “The factorial of 9 is 362880”

Negative number and zero include program using if. else

num = as.integer(readline(prompt=”Enter a number: “))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print(“Sorry,It is a Negative number”)
} else if(num == 0) {
print(“0!=1”)
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste(“The factorial of”, num ,”is”,factorial))

Output:
Enter a number: -1
[1] “Sorry, It is a Negative number”

or
Enter a number: 0
[1] “0!=1”

Built function:

> factorial(9)
[1] 362880

No Comments

Post a Reply