Harmonic series: Difference between revisions
Content added Content deleted
(Added rust section. This code is currently slow. The search through all the harmonic numbers when looking for when the series exceeds the different thresholds does not finish within a comfortable time frame on my laptop when the maximum threshold is 10.) |
|||
Line 1,639: | Line 1,639: | ||
The first harmonic number greater than 9 is 9.000208062931, at position 4550 |
The first harmonic number greater than 9 is 9.000208062931, at position 4550 |
||
The first harmonic number greater than 10 is 10.000043008276, at position 12367 |
The first harmonic number greater than 10 is 10.000043008276, at position 12367 |
||
</pre> |
|||
=={{header|Rust}}== |
|||
Using big rationals. |
|||
<lang rust> |
|||
use num::rational::Ratio; |
|||
use num::{BigInt, FromPrimitive}; |
|||
fn main() { |
|||
for n in 1..=20 { |
|||
println!("Harmonic number {} = {}", n, harmonic_number(n.into())); |
|||
} |
|||
println!("Harmonic number 100 = {}", harmonic_number(100.into())); |
|||
let max = 5; |
|||
let mut target = 1; |
|||
let mut i = 1; |
|||
while target <= max { |
|||
if harmonic_number(i.into()) > Ratio::from_integer(FromPrimitive::from_u64(target).unwrap()) |
|||
{ |
|||
println!("Position of first term > {} is {}", target, i); |
|||
target += 1; |
|||
} |
|||
i += 1; |
|||
} |
|||
} |
|||
fn harmonic_number(n: BigInt) -> Ratio<BigInt> { |
|||
let mut result: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(0).unwrap()); |
|||
let mut i: BigInt = FromPrimitive::from_u8(1).unwrap(); |
|||
let one: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(1).unwrap()); |
|||
while i <= n { |
|||
result = &result + &one / &i; |
|||
i += 1; |
|||
} |
|||
result |
|||
} |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
Harmonic number 1 = 1 |
|||
Harmonic number 2 = 3/2 |
|||
Harmonic number 3 = 11/6 |
|||
Harmonic number 4 = 25/12 |
|||
Harmonic number 5 = 137/60 |
|||
Harmonic number 6 = 49/20 |
|||
Harmonic number 7 = 363/140 |
|||
Harmonic number 8 = 761/280 |
|||
Harmonic number 9 = 7129/2520 |
|||
Harmonic number 10 = 7381/2520 |
|||
Harmonic number 11 = 83711/27720 |
|||
Harmonic number 12 = 86021/27720 |
|||
Harmonic number 13 = 1145993/360360 |
|||
Harmonic number 14 = 1171733/360360 |
|||
Harmonic number 15 = 1195757/360360 |
|||
Harmonic number 16 = 2436559/720720 |
|||
Harmonic number 17 = 42142223/12252240 |
|||
Harmonic number 18 = 14274301/4084080 |
|||
Harmonic number 19 = 275295799/77597520 |
|||
Harmonic number 20 = 55835135/15519504 |
|||
Harmonic number 100 = 14466636279520351160221518043104131447711/2788815009188499086581352357412492142272 |
|||
Position of first term > 1 is 2 |
|||
Position of first term > 2 is 4 |
|||
Position of first term > 3 is 11 |
|||
Position of first term > 4 is 31 |
|||
Position of first term > 5 is 83 |
|||
</pre> |
</pre> |
||