Skip to content
This repository was archived by the owner on Dec 20, 2024. It is now read-only.

Commit 4eda7c3

Browse files
authored
Merge pull request #1310 from tanjunchen/improve-code
enhancement: improve GCDSlice performance
2 parents ca96df3 + e73614c commit 4eda7c3

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

pkg/algorithm/algorithm.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,14 @@ func GCDSlice(s []int) int {
2727
if length == 1 {
2828
return s[0]
2929
}
30-
31-
return GCD(s[length-1], GCDSlice(s[:length-1]))
30+
commonDivisor := s[0]
31+
for i := 1; i < length; i++ {
32+
if commonDivisor == 1 {
33+
return commonDivisor
34+
}
35+
commonDivisor = GCD(commonDivisor, s[i])
36+
}
37+
return commonDivisor
3238
}
3339

3440
// GCD returns the greatest common divisor of x and y.

0 commit comments

Comments
 (0)