File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
src/main/java/com/thealgorithms/maths Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments