|
|
@@ -25,6 +25,8 @@ use mem::size_of; |
|
use ops::{Add, Sub, Mul, Div, Rem, Neg};
|
|
use ops::{Add, Sub, Mul, Div, Rem, Neg};
|
|
use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
|
|
use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
|
|
use option::{Option, Some, None};
|
|
use option::{Option, Some, None};
|
|
|
|
use num;
|
|
|
|
use clone;
|
|
|
|
|
|
/// The base trait for numeric types
|
|
/// The base trait for numeric types
|
|
pub trait Num: PartialEq + Zero + One
|
|
pub trait Num: PartialEq + Zero + One
|
|
|
@@ -319,11 +321,19 @@ trait_impl!(Unsigned for uint u8 u16 u32 u64) |
|
///
|
|
///
|
|
/// assert_eq!(num::pow(2i, 4), 16);
|
|
/// assert_eq!(num::pow(2i, 4), 16);
|
|
/// ```
|
|
/// ```
|
|
#[inline]
|
|
pub trait Pow {
|
|
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
|
|
/// Calcurate self * self * ... * self (exp times).
|
|
if exp == 1 { base }
|
|
fn pow(&self, mut exp: uint) -> Self;
|
|
else {
|
|
|
|
let mut acc = one::<T>();
|
|
/// Calcurate self * self.
|
|
|
|
fn sq(&self) -> Self;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<M: num::One + Mul<M, M> + clone::Clone> Pow for M {
|
|
|
|
#[inline]
|
|
|
|
fn pow(&self, mut exp: uint) -> M {
|
|
|
|
let mut base = self.clone();
|
|
|
|
let mut acc = num::one::<M>();
|
|
while exp > 0 {
|
|
while exp > 0 {
|
|
if (exp & 1) == 1 {
|
|
if (exp & 1) == 1 {
|
|
acc = acc * base;
|
|
acc = acc * base;
|
|
|
@@ -333,6 +343,12 @@ pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T { |
|
}
|
|
}
|
|
acc
|
|
acc
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn sq(&self) -> M {
|
|
|
|
let s = self.clone();
|
|
|
|
s * s
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
/// Numbers which have upper and lower bounds
|
|
/// Numbers which have upper and lower bounds
|
|
|
|
0 comments on commit
f125678