McCarthy.java


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


/******************************************************************************
 *  Compilation:  javac McCarthy.java
 *  Execution:    java McCarthy n
 *
 *  Reads an integer command-line argument n and computes McCarthy's 91
 *  function at n.
 *
 *  % java McCarthy 0
 *  91
 *
 *  % java McCarthy 10
 *  91
 *
 *  % java McCarthy 90
 *  91
 *
 *  % java McCarthy 91
 *  91
 *
 *  % java McCarthy 99
 *  91
 *
 *  % java McCarthy 100
 *  91
 *
 *  % java McCarthy 101
 *  91
 *
 *  % java McCarthy 102
 *  92
 *
 *  % java McCarthy 103
 *  93
 *
 *  % java McCarthy 104
 *  94
 *
 *
 ******************************************************************************/


public class McCarthy {

    public static int mcCarthy(int n) {
        if (n > 100)
            return n - 10;
        return mcCarthy(mcCarthy(n+11));
    }

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


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:19:56 EDT 2022.