Harmonic series: Difference between revisions

Made `harmonic_number` take in a NonZeroU64 to showcase type system
m (Add space between comment marker and text)
(Made `harmonic_number` take in a NonZeroU64 to showcase type system)
Line 1,816:
use num::rational::Ratio;
use num::BigInt;
use std::num::NonZeroU64;
 
fn main() {
for n in 1..=20 {
// `harmonic_number` takes the type `NonZeroU64`,
println!("Harmonic number {n} = {}", harmonic_number(n));
// which is just a normal u64 which is guaranteed to never be 0.
// We convert n into this type with `n.try_into().unwrap()`,
// where the unwrap is okay because n is never 0.
println!(
println!( "Harmonic number {n} = {}", harmonic_number(n));
harmonic_number(n.try_into().unwrap())
);
}
 
// The unwrap here is likewise okay because 100 is not 0.
println!("Harmonic number 100 = {}", harmonic_number(100));
println!(
println!( "Harmonic number 100 = {}", harmonic_number(100));
harmonic_number(100.try_into().unwrap())
);
 
// In order to avoid recomputing all the terms in the sum for every harmonic number
Line 1,838 ⟶ 1,850:
}
 
// Compute the next term in the harmonic series.
iter += 1;
harmonic_number += Ratio::from_integer(iter.into()).recip();
Line 1,844 ⟶ 1,856:
}
 
fn harmonic_number(n: u64NonZeroU64) -> Ratio<BigInt> {
// Convert each integer from 1 to n into an arbitrary precision rational number
// and sum their reciprocals.
(1..=n).map(|i| Ratio::from_integer(i.intoget()).recip()).sum()
.map(|i| Ratio::from_integer(i.into()).recip())
.sum()
}
</syntaxhighlight>
19

edits