Hi!
I am very new to Rust and coming from Python it's my first strongly typed language.
Would be great if I could get some feedback on my code, which computes the digit periodicity of inverse integers (as seen here).
// Compute sorted vector of divisors for given integer n.
fn divisors(n: usize) -> Vec<usize> {
if n == 0 {return vec![]};
let mut divs = vec![1, n];
// check all integers smaller than sqrt(n) + 1
for i in 2..(1 + (n as f64).sqrt() as usize) {
if n % i == 0 {
divs.push(i);
divs.push(n / i)
}
}
divs.sort();
divs.dedup(); // remove consecutive duplicates
divs
}
// find digit periodicity of inverse of n in given base.
// e.g. n=3 -> 1/5 =0.2 -> periodicity=0
// n=3 -> 1/3 =0.33333333333... -> periodicity=1
// n=37 -> 1/37 =0.02702702702... -> periodicity=3
fn period(n: usize, base: usize) -> usize {
if n==0 {return 0}; // otherwise divisors(n-1) won't work
for div in divisors(n-1).iter() {
if (usize::pow(base, *div as u32) % n) == 1 {
return *div;
}
}
0 // no periodicity otherwise
}
fn main() {
let number = 19;
let divs = divisors(number);
let period = period(number, 10);
println!("Computed divisors of {}: {:?}", number, divs);
println!("Digit periodicity of 1/{}: {:?}", number, period);
}
Unfortunately, because it has to compute pow(b, div) % n
(where b
is the base and div
the divisor of n-1
), it will overflow pretty fast.
- What types should I use to allow results for up to n=10^5? Is there a less expensive way to compute the modulo of a large power?
- Why does
usize::pow()
expect au32
as the second argument and notusize
? - Do you notice any abhorrent violations of decent coding style?
I am thankful for any feedback!
Cheers,
struppi