Skip to content

Commit 3219c40

Browse files
author
David Rajchenbach-Teller
committed
[Optim] int.rs: reimplemented pow with fast exponentiation
1 parent 0d43e90 commit 3219c40

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

src/lib/int.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,16 +73,19 @@ fn to_str(n: int, radix: uint) -> str {
7373
fn str(i: int) -> str { ret to_str(i, 10u); }
7474

7575
fn pow(base: int, exponent: uint) -> int {
76-
ret if exponent == 0u {
77-
1
78-
} else if base == 0 {
79-
0
80-
} else {
81-
let accum = base;
82-
let count = exponent;
83-
while count > 1u { accum *= base; count -= 1u; }
84-
accum
85-
};
76+
if exponent == 0u { ret 1; } //Not mathemtically true if [base == 0]
77+
if base == 0 { ret 0; }
78+
let my_pow = exponent;
79+
let acc = 1;
80+
let multiplier = base;
81+
while(my_pow > 0u) {
82+
if my_pow % 2u == 1u {
83+
acc *= multiplier;
84+
}
85+
my_pow /= 2u;
86+
multiplier *= multiplier;
87+
}
88+
ret acc;
8689
}
8790
// Local Variables:
8891
// mode: rust;

0 commit comments

Comments
 (0)