-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path009_power.sio
More file actions
53 lines (42 loc) · 1.11 KB
/
009_power.sio
File metadata and controls
53 lines (42 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//@ run-pass
// HumanEval 009: Fast Exponentiation
//
// Compute x^n using binary exponentiation (exponentiation by squaring).
// O(log n) multiplications. Handles non-negative exponents only.
fn power(base: i64, exp: i64) -> i64 with Mut, Div, Panic {
if exp == 0 { return 1 }
var result: i64 = 1
var b = base
var e = exp
while e > 0 {
if e % 2 == 1 {
result = result * b
}
b = b * b
e = e / 2
}
result
}
fn main() -> i64 with IO, Mut, Panic, Div {
// Test 1: x^0 = 1
assert(power(5, 0) == 1)
assert(power(0, 0) == 1)
// Test 2: x^1 = x
assert(power(7, 1) == 7)
// Test 3: 2^10 = 1024
assert(power(2, 10) == 1024)
// Test 4: 3^5 = 243
assert(power(3, 5) == 243)
// Test 5: 5^3 = 125
assert(power(5, 3) == 125)
// Test 6: 2^20 = 1048576
assert(power(2, 20) == 1048576)
// Test 7: 10^6 = 1000000
assert(power(10, 6) == 1000000)
// Test 8: 1^anything = 1
assert(power(1, 100) == 1)
// Test 9: 0^positive = 0
assert(power(0, 5) == 0)
println("009_power: ALL TESTS PASSED")
0
}