[Algorithms] – Calc of factorial as a good example of recursion in go

Following the code implementation.

func Factorial(n int) int {
   if n == 0 || n == 1 {
      return 1
   } else {
      return n * Factorial(n-1)
   }
}

Following its tests.

package algoTest

import (
   "github.com/stretchr/testify/assert"
   "testing"
)

func TestFactorial (t *testing.T) {

   assert.Equal(t, 1, Factorial(1))
   assert.Equal(t, 1, Factorial(0))
   assert.Equal(t, 24, Factorial(4))
   assert.Equal(t, 120, Factorial(5))

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s