Skip to content

Commit

Permalink
Add GCD to src/algorithms/math.go
Browse files Browse the repository at this point in the history
  • Loading branch information
NikitaShkaruba committed Jul 14, 2023
1 parent d9efbc9 commit 2240fec
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
6 changes: 5 additions & 1 deletion docs/algorithms/math.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

Ahh, math problems. I like them the least! :D

## Factorization
### Greatest common divisor (GCD)
GCD helps to find number `c` that both input numbers `a` and `b` can be divided. Takes `O(logn)` time if you use [Euclid's algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm).
You can also get GCD using [primes factorization](#primes-factorization) bu getting primes for the first and the second number, and finding the greatest one.

### Primes factorization

Prime number only has two factors - one and the number itself.
Opposite of prime is composite.
Expand Down
15 changes: 14 additions & 1 deletion src/algorithms/math.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
package algorithms

////////////////////////// Prime factors //////////////////////////
////////////////////////// Greatest common divider (GCD) //////////////////////////
// You can find this algorithms overview in docs/algorithms/math.md

func GCD(a, b int) int {
for b != 0 {
t := b
b = a % b
a = t
}

return a
}

////////////////////////// Primes factorization //////////////////////////
// You can find this algorithms overview in docs/algorithms/math.md

func GetPrimeFactors(number int, maxNumber int) []int {
Expand Down
7 changes: 7 additions & 0 deletions src/algorithms/math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ import (
"testing"
)

func TestGCD(t *testing.T) {
assert.Equal(t, 4, GCD(8, 12))
assert.Equal(t, 6, GCD(54, 24))
assert.Equal(t, 14, GCD(42, 56))
assert.Equal(t, 1, GCD(13, 48))
}

func TestGetPrimeFactors(t *testing.T) {
maxNumber := 10000

Expand Down

0 comments on commit 2240fec

Please sign in to comment.