Skip to content
This repository was archived by the owner on Sep 3, 2021. It is now read-only.

Commit 58a6669

Browse files
committed
Merge pull request #4 from EtienneBruines/master
Improved PowInt for performance by adding recursion
2 parents 1df3eda + 33daac5 commit 58a6669

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

math.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,16 @@
1414

1515
package com
1616

17-
// PowInt is int type of math.Pow function.
17+
// PowInt is int type of math.Pow function.
1818
func PowInt(x int, y int) int {
19-
num := 1
20-
for i := 0; i < y; i++ {
21-
num *= x
19+
if y <= 0 {
20+
return 1
21+
} else {
22+
if y % 2 == 0 {
23+
sqrt := PowInt(x, y/2)
24+
return sqrt * sqrt
25+
} else {
26+
return PowInt(x, y-1) * x
27+
}
2228
}
23-
return num
2429
}

math_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright 2014 com authors
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License"): you may
4+
// not use this file except in compliance with the License. You may obtain
5+
// a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11+
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12+
// License for the specific language governing permissions and limitations
13+
// under the License.
14+
15+
package com
16+
17+
import (
18+
"testing"
19+
"math"
20+
"math/rand"
21+
)
22+
23+
func TestPow(t *testing.T) {
24+
for x := 0; x < 10; x++ {
25+
for y := 0; y < 8; y++ {
26+
result := PowInt(x, y)
27+
result_float := math.Pow(float64(x), float64(y))
28+
if result != int(result_float) {
29+
t.Errorf("Unable to correctly compute %d to the power of %d. Expected: %d, got %d. ", x, y, int(result_float), result)
30+
}
31+
}
32+
}
33+
}
34+
35+
func BenchmarkPow(b *testing.B) {
36+
x := rand.Intn(100)
37+
y := rand.Intn(6)
38+
b.ResetTimer()
39+
for n := 0; n < b.N; n++ {
40+
PowInt(x, y)
41+
}
42+
}

0 commit comments

Comments
 (0)