class E1 { /** Return the sum of the squares from 1 to n. Requires: n >= 1. */ public static int s(int n) { return (n == 1) ? 1 : s(n-1) + n*n; } } /* Pedagogical notes: * * The two calculations are: * k^2 + ((k+1)^2 + ((k+2)^2 + (... + (n^2))...)) * (...(((k^2) + (k+1)^2) + (k+2)^2) + ...) + n^2 * * The order of the arguments to + in the code has no effect on the order of operations, * but reflects the order of the numbers k^2, ..., n^2. * * Exercise: rearrange the above and the code so that the only difference is counting * from k to n versus n to k. * * Exercise: simplify the code by extending the domain to k = n+1. */ class E2 { /** Return the sum of the squares from k to n. Requires: k <= n. */ public static int sk(int k, int n) { return (k == n) ? k*k : k*k + sk(k+1, n); } /** Return the sum of the squares from k to n. Requires: k <= n. */ public static int sn(int k, int n) { return (k == n) ? n*n : sn(k, n-1) + n*n; } } /* Pedagogical notes: * * Calculates it as (...(((1^2) + 2^2) + 3^2) + ...) + n^2 * by passing along the current subtotal. * Notice syntactic clues to this in the code: sumSoFar on left of +, n*n * * Exercise: simplify by extending the domain of s and/or sHelper. */ class E3 { /** Return the sum of the squares from 1 to n. Requires: n >= 1. */ public static int s(int n) { return sHelper(0, 1, n); } /** Return sumSoFar + next^2 + (next+1)^2 + ... + n^2. Requires: 1 <= next <= n. */ public static int sHelper(int sumSoFar, int next, int n) { return (next == n) ? sumSoFar + n*n : sHelper(sumSoFar + next*next, next+1, n); } } /* Pedagogical notes: * * Calculates it as 1^2 + (2^2 + (3^2 + (... + (n^2))...)) * by passing along the current subtotal. * Notice syntactic clues to this in the code: sumSoFar on right of +, 1*1 * * Exercise: do something analagous to the exercises mentioned in E2 and E3. */ class E4 { /** Return the sum of the squares from 1 to n. Requires: n >= 1. */ public static int s(int n) { return sHelper(0, n); } /** Return 1^2 + 2^2 + ... + next^2 + sumSoFar. Requires: 1 <= next. */ public static int sHelper(int sumSoFar, int next) { return (next == 1) ? 1*1 + sumSoFar : sHelper(next*next + sumSoFar, next-1); } }