Skip to content

Commit

Permalink
Fast powering implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
TannerGabriel committed Apr 21, 2020
1 parent 4515a10 commit 41ce2e8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
22 changes: 22 additions & 0 deletions algorithms/math/FastPowering/fastpowering.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package FastPowering

import (
"math"
)

func fastPowering(base float64, power int) float64 {
// Anything raised to the power of zero is 1
if power == 0 {
return 1
}

// Even powers are redefined via two smaller powers
if power%2 == 0 {
multiplier := fastPowering(base, power/2)
return multiplier * multiplier
}

// Odd powers
multiplier := fastPowering(base, int(math.Floor(float64(power/2))))
return multiplier * multiplier * base
}
21 changes: 21 additions & 0 deletions algorithms/math/FastPowering/fastpowering_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package FastPowering

import (
"testing"
)

func TestFastPowering(t *testing.T) {
data := []struct {
n float64
k int
want float64
}{
{1, 0, 1}, {2, 2, 4}, {2, 10, 1024}, {3, 3, 27}, {10, 0, 1}, {16, 16, 18446744073709552000},
}

for _, d := range data {
if got := fastPowering(d.n, d.k); got != d.want {
t.Errorf("Invalid value for N: %f, got: %f, want: %f", d.n, got, d.want)
}
}
}

0 comments on commit 41ce2e8

Please sign in to comment.