Math function help

I looked in The Book and StackOverflow, but still can't get this to work.

I want to translate this Crystal method to Rust.
n is an integer of usize, as well as the output, and log() is the natural log.

def approx_nthprime(n)
  b, logn = (0.5722 * (n**0.0088)), Math.log(n)
  a = b * Math.log(logn)
  (n * (logn + a) + 3).to_u64
end

fn approx_nthprime(n: usize) -> usize {
  let (b, logn) = (0.5722 * (n**0.0088), log(n));
  let a = b * log(logn); 
  (n * (logn + a) + 3) as usize
}

Thanks in advance.

Try looking at the std library docs: f64 - Rust

  • You need to explicitly convert to float
  • Natural log is called ln
  • ln is a method instead of a free function
  • power is also a method, powf
pub fn approx_nthprime(n: usize) -> usize {
    let n = n as f64;
    let (b, logn) = (0.5722 * n.powf(0.0088), n.ln());
    let a = b * logn.ln();
    (n * (logn + a) + 3.0) as usize
}
1 Like

I had everything you had except I didn't first convert n to floating point.
Now I know what that error message meant.

If we every meet, I'll buy you a drink of your choice. :yum:

1 Like