Harmonic.java


Below is the syntax highlighted version of Harmonic.java from §2.3 Recursion.


/*************************************************************************
 *  Compilation:  javac Harmonic.java
 *  Execution:    java Harmonic N
 *  
 *  Compute the Nth Harmonic number = 1 + 1/2 + 1/3 + ... + 1/N.
 *
 *  % java Harmonic 5
 *  2.283333333333333
 *
 *  % java Harmonic 100
 *  5.187377517639621
 *
 *  %  java Harmonic 10000
 *  Exception in thread "main" java.lang.StackOverflowError
 *
 *  // the -Xss flag increases the stack size
 *  %  java -Xss8192k Harmonic 10000
 *  89.787606036044348
 *
 *  % java -Xss8192k Harmonic 1000000
 *  Exception in thread "main" java.lang.StackOverflowError
 *
 *************************************************************************/

public class Harmonic {

    public static double H(int N) {
        if (N == 1) return 1.0;
        return H(N-1) + 1.0/N;
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        StdOut.println(H(N));
    }
}



Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.
Last updated: Wed Feb 9 09:05:37 EST 2011.