use crate::fraction::Fraction;
pub trait GetDecimal {
fn get_decimal(&self) -> u128;
}
macro_rules! impl_get_decimal {
($name:ident for $($t:ty)*) => ($(
impl $name for $t {
fn get_decimal(&self) -> u128 {
if self.floor().to_string() != self.to_string() {
let decimalstring = &self.to_string()[(self.floor()).to_string().len()+1..];
let decimalnumber = decimalstring.parse::<u128>().unwrap();
return decimalnumber;
} else {
return 0u128;
}
}
}
)*)
}
impl_get_decimal!(GetDecimal for f32 f64);
pub trait BetterExponent {
fn power(self, number: usize) -> Self;
}
macro_rules! impl_better_exponent {
($name:ident for $($t:ty)*) => ($(
impl $name for $t {
fn power(self, number: usize) -> Self {
let mut result = 1usize;
for _ in 1..=number {
result *= self as usize;
}
return result as Self;
}
}
)*)
}
impl_better_exponent!(BetterExponent for u8 u16 u32 u64 u128);
pub trait VecToFraction {
fn to_fraction(self) -> Vec<Fraction>;
}
macro_rules! impl_vec_to_fraction {
($name:ident for $($t:ty)*) => ($(
impl $name for Vec<$t> {
fn to_fraction(self) -> Vec<Fraction> {
let mut result = vec![];
for x in self {
result.push(Fraction::from_float(x as f64));
}
return result;
}
}
)*)
}
impl_vec_to_fraction!(VecToFraction for u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 usize f32 f64);
pub trait GCD {
fn gcd(self, other: Self) -> Self;
}
macro_rules! impl_gcd {
($name:ident for $($t:ty)*) => ($(
impl $name for $t {
fn gcd(self, other: Self) -> Self {
let mut m = self;
let mut n = other;
if m == 0 || n == 0 {
return (m | n).abs();
}
let shift = (m | n).trailing_zeros();
if m == Self::min_value() || n == Self::min_value() {
return ((1 << shift) as $t).abs();
}
m = m.abs();
n = n.abs();
m >>= m.trailing_zeros();
n >>= n.trailing_zeros();
while m != n {
if m > n {
m -= n;
m >>= m.trailing_zeros();
} else {
n -= m;
n >>= n.trailing_zeros();
}
}
m << shift
}
}
)*)
}
impl_gcd!(GCD for i8 i16 i32 i64 i128 isize);