DEV Community

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

Posted on

3 2

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)

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay