-
-
Notifications
You must be signed in to change notification settings - Fork 129
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4515a10
commit 41ce2e8
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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 | ||
} |
This file contains 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
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) | ||
} | ||
} | ||
} |