Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class IterativeSummer {
- /**
- * Returns a sum, computed iteratively.
- *
- * @param x the augend
- * @param y the addend
- * @return the sum of the augend and addend
- */
- public int iterativeSumDriver(int x, int y) {
- int[] result = iterativeSumInternal(x,y);
- while (result.length == 2) {
- result = iterativeSumInternal(result[0], result[1]);
- }
- return result[0];
- }
- /**
- * Returns the new computation state of a iterative sum
- * computation. If x is 0, then returns an array of just y.
- * Otherwise, returns an an array of x-1 and y+1.
- *
- * @param x the augend
- * @param y the addend
- * @return the next interal state
- */
- int[] iterativeSumInternal(int x, int y) {
- if (x == 0) {
- return new int[] { y };
- }
- else {
- return new int[] { x-1, y+1 };
- }
- }
- public static void main(String[] args) {
- int x = 5;
- int y = 6;
- int sum = new IterativeSummer().iterativeSumDriver(x,y);
- System.out.println(String.format("%d + %d = %d", x, y, sum));
- }
- }
Add Comment
Please, Sign In to add comment