Write a program GeneralizedHarmonic.java that takes two integer command-line arguments n and r and uses a for loop to compute the nth generalized harmonic number of order r, which is defined by the following formula:
H(n, r) = 1 / 1r + 1 / 2r + ⋯ + 1 / nr.
For example, H(3, 2) = 1 / 12 + 1 / 22 + 1 / 32 = 4936 ≈ 1.361111.
~/Desktop/loops> java GeneralizedHarmonic 1 1
1.0
~/Desktop/loops> java GeneralizedHarmonic 2 1
1.5
~/Desktop/loops> java GeneralizedHarmonic 3 1
1.8333333333333333
~/Desktop/loops> java GeneralizedHarmonic 1 2
1.0
~/Desktop/loops> java GeneralizedHarmonic 2 2
1.25
~/Desktop/loops> java GeneralizedHarmonic 3 2
1.3611111111111112
Note: you may assume that n is a positive integer.
The generalized harmonic numbers are closely related to the Riemann zeta function, which plays a central role in number theory.
public class GeneralizedHarmonic {
public static void main(String[] args) {
final int n = Integer.parseInt(args[0]);
final int r = Integer.parseInt(args[1]);
double sum = 0.0;
for (int i = 1; i <= n; i++) {
sum = sum + (1 / Math.pow(i, r));
}
System.out.println(sum);
}
}
Link To: Java Source Code