Skip to content

Commit 23ee708

Browse files
author
Farai Mugaviri
committed
Added a harmonic number calculation algorithm
1 parent 39b0944 commit 23ee708

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* A class for calculating harmonic numbers.
5+
* The harmonic series is the divergent infinite series: 1 + 1/2 + 1/3 + 1/4 + ...
6+
*/
7+
public final class HarmonicNumber {
8+
9+
private HarmonicNumber() {}
10+
11+
/**
12+
* Calculates the nth harmonic number.
13+
* The harmonic series is the sum: 1 + 1/2 + 1/3 + ... + 1/n
14+
* This series appears in various mathematical and practical applications.
15+
*
16+
* For example:
17+
* H(1) = 1
18+
* H(2) = 1 + 1/2 = 1.5
19+
* H(3) = 1 + 1/2 + 1/3 ≈ 1.833
20+
* H(4) = 1 + 1/2 + 1/3 + 1/4 ≈ 2.083
21+
*
22+
* @param numTerms the number of terms to sum (n)
23+
* @return the nth harmonic number
24+
* @throws IllegalArgumentException if numTerms is less than 1
25+
*/
26+
public static double of(int numTerms) {
27+
if (numTerms < 1) {
28+
throw new IllegalArgumentException("Number of terms must be positive");
29+
}
30+
double harmonicSum = 0.0;
31+
for (int termIndex = 1; termIndex <= numTerms; termIndex++) {
32+
harmonicSum += 1.0 / termIndex;
33+
}
34+
return harmonicSum;
35+
}
36+
}

0 commit comments

Comments
 (0)