Harmonic series: Difference between revisions

Made code more idiomatic and sped it up such that it can now compute the stretch task.
m (syntax highlighting fixup automation)
(Made code more idiomatic and sped it up such that it can now compute the stretch task.)
Line 1,763:
<syntaxhighlight lang="rust">
use num::rational::Ratio;
use num::{BigInt, FromPrimitive};
 
fn main() {
for n in 1..=20 {
println!("Harmonic number {n} = {}", n, harmonic_number(n.into()));
}
 
println!("Harmonic number 100 = {}", harmonic_number(100.into()));
 
//In order to avoid recomputing all the terms in the sum for the nth harmonic number
//we save the value of the harmonic series between loop iterations
//and just add 1/iter to it.
 
let max = 5;
let mut target = 1;
let mut iiter = 1;
let mut resulth: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(0)1.unwrapinto());
while target <= max {
 
if harmonic_number(i.into()) > Ratio::from_integer(FromPrimitive::from_u64(target).unwrap())
while target <= 10 {
if harmonic_number(i.into())h > Ratio::from_integer(FromPrimitive::from_u64(target).unwrapinto()) {
println!("Position of first term > {target} is {iter}", target, i);
target += 1;
}
 
i += 1;
//Compute the next term in the harmonic series
iiter += 1;
h += Ratio::from_integer(iter.into()).recip();
}
}
 
fn harmonic_number(n: BigIntu64) -> Ratio<BigInt> {
//Convert each integer from 1 to n into an arbitrary precision rational number
let mut result: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(0).unwrap());
//and sum their reciprocals
let mut i: BigInt = FromPrimitive::from_u8(1).unwrap();
let one: Ratio<BigInt> (1..=n).map(|i| Ratio::from_integer(FromPrimitive::from_u8i.into(1)).unwraprecip());.sum()
 
while i <= n {
result = &result + &one / &i;
i += 1;
}
 
result
}
</syntaxhighlight>
Line 1,827:
Position of first term > 4 is 31
Position of first term > 5 is 83
Position of first term > 6 is 227
Position of first term > 7 is 616
Position of first term > 8 is 1674
Position of first term > 9 is 4550
Position of first term > 10 is 12367
</pre>
 
 
=={{header|Verilog}}==
19

edits