diff options
| author | David Rajchenbach-Teller <dteller@mozilla.com> | 2011-10-12 10:22:26 +0200 |
|---|---|---|
| committer | David Rajchenbach-Teller <dteller@mozilla.com> | 2011-10-12 10:56:05 +0200 |
| commit | 3219c40e18c20a0dbd41b106e1b05e3696bf4c85 (patch) | |
| tree | 6d2a6e1847a490002c063d7be964419ceae69194 | |
| parent | 0d43e90172c364a5f92a0f4447a5030274f18832 (diff) | |
[Optim] int.rs: reimplemented pow with fast exponentiation
| -rw-r--r-- | src/lib/int.rs | 23 |
1 files changed, 13 insertions, 10 deletions
diff --git a/src/lib/int.rs b/src/lib/int.rs index 0a6e69ceadc..fe7689e3e28 100644 --- a/src/lib/int.rs +++ b/src/lib/int.rs @@ -73,16 +73,19 @@ fn to_str(n: int, radix: uint) -> str { fn str(i: int) -> str { ret to_str(i, 10u); } fn pow(base: int, exponent: uint) -> int { - ret if exponent == 0u { - 1 - } else if base == 0 { - 0 - } else { - let accum = base; - let count = exponent; - while count > 1u { accum *= base; count -= 1u; } - accum - }; + if exponent == 0u { ret 1; } //Not mathemtically true if [base == 0] + if base == 0 { ret 0; } + let my_pow = exponent; + let acc = 1; + let multiplier = base; + while(my_pow > 0u) { + if my_pow % 2u == 1u { + acc *= multiplier; + } + my_pow /= 2u; + multiplier *= multiplier; + } + ret acc; } // Local Variables: // mode: rust; |
