Harmonic series: Difference between revisions
Made code more idiomatic and sped it up such that it can now compute the stretch task.
Thundergnat (talk | contribs) 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::
fn main() {
for n in 1..=20 {
println!("Harmonic number {n} = {}"
}
println!("Harmonic number 100 = {}", harmonic_number(100
//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 mut target = 1;
let mut
if harmonic_number(i.into()) > Ratio::from_integer(FromPrimitive::from_u64(target).unwrap())▼
while target <= 10 {
▲ if
println!("Position of first term > {target} is {iter}"
target += 1;
}
i += 1;▼
//Compute the next term in the harmonic series
h += Ratio::from_integer(iter.into()).recip();
}
}
fn harmonic_number(n:
//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
}
</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}}==
|