Created
September 29, 2020 15:23
-
-
Save sarthakpranesh/8185f1abe29f77c6a3326e9adc734fa1 to your computer and use it in GitHub Desktop.
#100DayOfCode - Day 43/100 - GCD algo stress test
This file contains hidden or 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" | |
"math/rand" | |
) | |
func main() { | |
var gChan chan int = make(chan int) | |
var geChan chan int = make(chan int) | |
for { | |
a := rand.Intn(100000) | |
b := rand.Intn(100000) | |
fmt.Printf("Val a,b: %v, %v\t", a, b) | |
go func() { | |
g := gcd(a, b) | |
fmt.Printf("GCD: %v\t", g) | |
gChan <- g | |
}() | |
go func() { | |
ge := gcdEfficient(a, b) | |
fmt.Printf("GCD-E: %v\t", ge) | |
geChan <- ge | |
}() | |
if <-gChan != <-geChan { | |
fmt.Printf("Result: False\n") | |
break | |
} | |
fmt.Printf("Result: True\n") | |
} | |
} | |
// slow algorithm for very large number such as 63473574 | |
func gcd(a, b int) int { | |
if a == 0 { | |
return b | |
} | |
if b == 0 { | |
return a | |
} | |
r := 1 | |
var smaller int | |
if a < b { | |
smaller = a | |
} else { | |
smaller = b | |
} | |
for i := 1; i <= smaller; i++ { | |
if a%i == 0 && b%i == 0 { | |
r = i | |
} | |
} | |
return r | |
} | |
// Euclidean algorithm | |
func gcdEfficient(a, b int) int { | |
if b == 0 { | |
return a | |
} | |
at := a % b | |
return gcdEfficient(b, at) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment