Skip to content

Commit 05166ab

Browse files
authored
Implemented GCD in Go (#5025)
* Added GCD in Go * Updated README.md
1 parent ef00e20 commit 05166ab

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

Go/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
- [Ugly Number](math/Ugly_Number)
5151
- [Fibonacci Number](math/Fibonacci)
5252
- [Mystery Number](math/Mystery_Number)
53+
- [GCD](math/GCD)
5354

5455
## Others
5556
- [Tower of Hanoi](other/tower_of_hanoi)

Go/math/GCD/GCD.go

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/* This program calculates the GCD(Greatest Common Divisor)
2+
of two numbers given as input.*/
3+
4+
package main
5+
6+
import (
7+
"fmt"
8+
)
9+
10+
// This function finds the minimum of two numbers and returns it
11+
func min(n1, n2 int) int {
12+
if(n1 < n2) {
13+
return n1
14+
} else {
15+
return n2
16+
}
17+
}
18+
19+
// This function calculates the GCD.
20+
func is_gcd(n1, n2 int) int {
21+
22+
// Find the minimum of two numbers
23+
var min int = min(n1, n2)
24+
var result int
25+
26+
// Iterate till the minimum
27+
for i := 1; i <= min; i++ {
28+
// It it divides both n1 and n2
29+
if(n1 % i == 0 && n2 % i == 0) {
30+
// Set it as gcd
31+
result = i
32+
}
33+
}
34+
// After completion return the GCD
35+
return result
36+
}
37+
38+
func main() {
39+
40+
// Take two numbers as input from the user
41+
fmt.Print("Enter two numbers followed by spaces: ")
42+
var n1, n2 int
43+
fmt.Scan(&n1, &n2)
44+
45+
// Call the GCD function
46+
var result int = is_gcd(n1, n2)
47+
48+
// Print the result
49+
fmt.Print("\nGCD of ", n1, " and ", n2, " is ", result, "\n")
50+
}
51+
52+
/* Sample I/O:
53+
54+
Enter two numbers followed by spaces: 100 12
55+
56+
GCD of 100 and 12 is 4
57+
58+
*/

0 commit comments

Comments
 (0)