Calculate the double factorial of a number in go!!

Golang

 The double factorial of a number, denoted as n!!, refers to the product of all positive integers from 1 to n, but including only the odd numbers. Calculating the double factorial is a straightforward process in Go. Below, we'll show you how to do it with a concise example of code:


Go Playground link

package main


import "fmt"


func calculateDoubleFactorial(n int) int {

    result := 1


    // Start from n and decrement by 2 until reaching 1 or 0.

    for n >= 1 {

        result *= n

        n -= 2

    }


    return result

}


func main() {

    number := 5 // Change this value to the desired number.

    result := calculateDoubleFactorial(number)


    fmt.Printf("The double factorial of %d is %d\n", number, result)

}


In this Go code, we've defined a function called `calculateDoubleFactorial` that takes an integer `n` as input and calculates its double factorial. We use a `for` loop to multiply all odd numbers from `n` down to 1 or 0, decrementing `n` by 2 in each iteration. Finally, the result is returned and displayed in the `main` function of the program.


If you run this code with `number` set to 5, you'll get the double factorial of 5, which is 15. You can change the value of `number` according to your needs to calculate the double factorial of any positive integer. We hope this code helps you understand how to calculate the double factorial in Go efficiently and easily!

Comments