DEV Community

Cover image for Find the Factorial of a Number(JS AND Golang)
Neeraj Kumar
Neeraj Kumar

Posted on

Find the Factorial of a Number(JS AND Golang)

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))
Enter fullscreen mode Exit fullscreen mode

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 
}
Enter fullscreen mode Exit fullscreen mode

method:(Using Recursion in JS)

function factorialRecursive(number) {
  return number > 1 ? number * factorialRecursive(number - 1) : 1;
}
console.log(factorialRecursive(5))
Enter fullscreen mode Exit fullscreen mode

method:(Using Recursion in Golang)


Enter fullscreen mode Exit fullscreen mode

Top comments (0)