javaloopsfor-loopinfinity

For-loop returning wrong results


I am getting wrong results resolving below task:

Generalized harmonic numbers. 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: formula


public class GeneralizedHarmonic {

    public static void main(String[] args) {

        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int i;
        double sum = 0;
        for (i = 0; i <= a; i++) {
            sum += 1 / Math.pow(i, b);
        }
        System.out.println(sum);
    }
}

This is my code but I could not get the correct test output.The output result is always Infinity. test outputs


Solution

  • You have initliazed int i = 0 in for-loop for (i = 0; i <= a; i++) and so the first element of your harmonic number isn't \frac{1}{1^{b}}, but ![\frac{1}{0^{b}}.

    The code that works:

    public class GeneralizedHarmonic {
    
        public static void main(String[] args) {
    
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            double sum = 0;
            for (int i = 1; i <= a; i++) {
                sum += 1 / Math.pow(i, b);
            }
            System.out.println(sum);
        }
    }