Skip to content

Commit 922f693

Browse files
brsongraydon
authored andcommitted
Add _int.pow
1 parent ac72f42 commit 922f693

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/lib/_int.rs

+17
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,23 @@ fn to_str(mutable int n, uint radix) -> str
3434
}
3535
}
3636
37+
fn pow(int base, uint exponent) -> int {
38+
39+
if (exponent == 0u) {
40+
ret 1;
41+
} else if (base == 0) {
42+
ret 0;
43+
} else {
44+
auto accum = base;
45+
auto count = exponent;
46+
while (count > 1u) {
47+
accum *= base;
48+
count -= 1u;
49+
}
50+
ret accum;
51+
}
52+
}
53+
3754
// Local Variables:
3855
// mode: rust;
3956
// fill-column: 78;

src/test/run-pass/lib-int.rs

+11
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,17 @@ fn test_to_str() {
1111
check (eq(_int.to_str(100, 10u), "100"));
1212
}
1313

14+
fn test_pow() {
15+
check (_int.pow(0, 0u) == 1);
16+
check (_int.pow(0, 1u) == 0);
17+
check (_int.pow(0, 2u) == 0);
18+
check (_int.pow(-1, 0u) == -1);
19+
check (_int.pow(1, 0u) == 1);
20+
check (_int.pow(-3, 2u) == 9);
21+
check (_int.pow(-3, 3u) == -27);
22+
check (_int.pow(4, 9u) == 262144);
23+
}
24+
1425
fn main() {
1526
test_to_str();
1627
}

0 commit comments

Comments
 (0)