Last active
April 15, 2018 16:46
-
-
Save Mardiniii/f1a5b7e9c82bc206cc11f3b4dfaca61f to your computer and use it in GitHub Desktop.
Snippet for medium post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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