Skip to content

Instantly share code, notes, and snippets.

@Mardiniii
Last active April 15, 2018 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mardiniii/f1a5b7e9c82bc206cc11f3b4dfaca61f to your computer and use it in GitHub Desktop.
Save Mardiniii/f1a5b7e9c82bc206cc11f3b4dfaca61f to your computer and use it in GitHub Desktop.
Snippet for medium post
package main
import "fmt"
// Factorial recursive function to find the factorial result
// using go routines and the channel passed as parameter
func Factorial(number int, product int, ch chan int) {
// Calculate the product until this point
product = product * number
// If the number if one we are done and the factorial is finished
if number == 1 {
// Send through the channel the factorial result
ch <- product
// Stop the execution since we found what we were looking for
return
}
// Recursive call for the next value sendig the new number and
// the current value of the product
go Factorial(number-1, product, ch)
}
func main() {
ch := make(chan int)
number := 5
// First call to Factorial recursive function
go Factorial(number, 1, ch)
// Read from the channel when the value is already computed
answer := <-ch
fmt.Printf("%d!= %d\n", number, answer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment