Harmonic series: Difference between revisions
Content added Content deleted
(Made code more idiomatic and sped it up such that it can now compute the stretch task.) |
m (Clarified comment and the name of the harmonic_series variable) |
||
Line 1,772: | Line 1,772: | ||
println!("Harmonic number 100 = {}", harmonic_number(100)); |
println!("Harmonic number 100 = {}", harmonic_number(100)); |
||
//In order to avoid recomputing all the terms in the sum for |
//In order to avoid recomputing all the terms in the sum for every harmonic number |
||
//we save the value of the harmonic series between loop iterations |
//we save the value of the harmonic series between loop iterations |
||
//and just add 1/iter to it. |
//and just add 1/iter to it. |
||
Line 1,778: | Line 1,778: | ||
let mut target = 1; |
let mut target = 1; |
||
let mut iter = 1; |
let mut iter = 1; |
||
let mut |
let mut harmonic_number: Ratio<BigInt> = Ratio::from_integer(1.into()); |
||
while target <= 10 { |
while target <= 10 { |
||
if |
if harmonic_number > Ratio::from_integer(target.into()) { |
||
println!("Position of first term > {target} is {iter}"); |
println!("Position of first term > {target} is {iter}"); |
||
target += 1; |
target += 1; |
||
Line 1,788: | Line 1,788: | ||
//Compute the next term in the harmonic series |
//Compute the next term in the harmonic series |
||
iter += 1; |
iter += 1; |
||
harmonic_number += Ratio::from_integer(iter.into()).recip(); |
|||
} |
} |
||
} |
} |