/* * T12n02.java: Summing the integers from 1 through n. * * This is an example of a task that can be done with iteration or with * recursion, both with roughly equal ease. More importantly, it is an * example of a task that requires neither iteration nor recursion! * The sum can be computed using Gauss' result, which requires just three * operations no matter the size of n. Knowing some math ain't a bad thing! * * A point of trivia: Even though the Gaussian solution is efficient, due * to the way it is coded here, it can't handle values of n as large as * those that the others can handle (try n=50000, for instance). Can you * change the implementation so that it can solve larger problems? */ import java.util.*; public class T12n02 { /* * sumIterative(n) -- Computes the sum of the first n positive * integers iteratively and returns it. * * Precondition: n is a non-negative integer * Postcondition: sum of the first n positive integers is returned */ public static long sumIterative(int n) { long sum = 0; // holds running sum of the integer sequence for (int i = 1; i <= n; i++) { sum += i; } return sum; } /* * sumRecursive(n) -- Computes the sum of the first n positive * integers recursively and returns it. * * Precondition: n is a non-negative integer small enough not to * cause a StackOverflowError exception on your system * Postcondition: sum of the first n positive integers is returned */ public static long sumRecursive(int n) { if (n == 1) // Base case of sun(1..1) = 1 return 1; else // General case of sum(1..n) = sum(1..n-1) + n return n + sumRecursive(n-1); } /* * sumGauss(n) -- Computes the sum of the first n positive * integers using Gauss' formula [0.5 * n * (n+1)] and returns it. * * Precondition: n is a non-negative integer * Postcondition: sum of the first n positive integers is returned */ public static long sumGauss(int n) { return n * (n+1) / 2; } public static void main (String [] args) { if (args.length < 1) { System.out.println("\n\tUSAGE: java T12n02 and the sum " + "1 + 2 + ... + |n| will be displayed.\n"); System.exit(1); } int n = Math.abs(Integer.parseInt(args[0])); System.out.println("Iteratively, sum(1.." + n + ") = " + sumIterative(n)); if (n != 0) { System.out.println("Recursively, sum(1.." + n + ") = " + sumRecursive(n)); } else { System.out.println("Recursively, sum(1..0) would cause trouble!"); } System.out.println(" Gaussily, sum(1.." + n + ") = " + sumGauss(n)); } }