joshuataylor

example for http://stackoverflow.com/q/39339015/1281433

Sep 6th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. public class IterativeSummer {
  2.     /**
  3.      * Returns a sum, computed iteratively.
  4.      *
  5.      * @param x the augend
  6.      * @param y the addend
  7.      * @return the sum of the augend and addend
  8.      */
  9.     public int iterativeSumDriver(int x, int y) {
  10.         int[] result = iterativeSumInternal(x,y);
  11.         while (result.length == 2) {
  12.             result = iterativeSumInternal(result[0], result[1]);
  13.         }
  14.         return result[0];
  15.     }
  16.    
  17.     /**
  18.      * Returns the new computation state of a iterative sum
  19.      * computation.  If x is 0, then returns an array of just y.
  20.      * Otherwise, returns an an array of x-1 and y+1.
  21.      *
  22.      * @param x the augend
  23.      * @param y the addend
  24.      * @return the next interal state
  25.      */
  26.     int[] iterativeSumInternal(int x, int y) {
  27.         if (x == 0) {
  28.             return new int[] { y };
  29.         }
  30.         else {
  31.             return new int[] { x-1, y+1 };
  32.         }
  33.     }
  34.    
  35.     public static void main(String[] args) {
  36.         int x = 5;
  37.         int y = 6;
  38.         int sum = new IterativeSummer().iterativeSumDriver(x,y);
  39.         System.out.println(String.format("%d + %d = %d", x, y, sum));
  40.     }
  41. }
Add Comment
Please, Sign In to add comment