factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. example:
5! = 5 * 4 * 3 * 2 * 1 = 120
simple method: 1(JS)
function factorial(number) {
let result = 1;
for (let i = 2; i <= number; i += 1) {
result *= i;
}
return result;
}
console.log(factorial(5))
simple method: 1(Golang)
var factVal uint64 = 1 // uint64 is the set of all unsigned 64-bit integers.
var i int = 1
var n int
func factorial(n int) uint64 {
if(n < 0){
fmt.Print("Factorial of negative number doesn't exist.")
}else{
for i:=1; i<=n; i++ {
factVal *= uint64(i)
}
}
return factVal
}
method:(Using Recursion in JS)
function factorialRecursive(number) {
return number > 1 ? number * factorialRecursive(number - 1) : 1;
}
console.log(factorialRecursive(5))
method:(Using Recursion in Golang)
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
Top comments (0)