Skip to content

Commit 4bc5b24

Browse files
committed
Create fastExponent.go
1 parent c8d63ef commit 4bc5b24

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

math/fastExponent.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
//based on square and multiply algorithm
4+
5+
func fastExponentiation(b int, e int)float64{
6+
//runs in O(log(n)) where n = e
7+
if e == 0{
8+
return 1.0
9+
}
10+
if e == 1{
11+
return float64(b)
12+
}
13+
if e<0{
14+
e*=-1
15+
println("executed")
16+
return 1/fastExponentiation(b,e)
17+
}
18+
r:=1
19+
for ;e>0;{
20+
if e%2==1{
21+
r=r*b
22+
}
23+
e =e>>1
24+
b = b*b
25+
}
26+
return float64(r)
27+
}
28+
29+
func main(){
30+
print(fastExponentiation(2,0))
31+
}

0 commit comments

Comments
 (0)