How can I make this Peano addition algorithm work without using a loop?

427 Views Asked by At

Can someone please explain how to do make this work without a loop?

let x = prompt("Enter a first number to add:");
let y = prompt("Enter a second number to add:");
parseFloat(x);
parseFloat(y);

alert(peanoAddition(x, y));

function peanoAddition(x, y) {
  while (y !== 0) {
    if (y === 0) {
      return x;
    } else {
      x = x + 1;
      y = y - 1;
      return x;
    }
  }
}

1

There are 1 best solutions below

1
Ian On

This is fairly simple to change to a recursive function. Your terminating condition will be the same: if (y === 0) return x. Otherwise, you just call peanoAddition again with the new arguments for x and y and return the result.

Then, if y is not 0, the function gets called again and again until y is 0.

The following works exactly the same as your code. However, it keeps the same issues as well. For example, what happens when you call peanoAddition(5, -2)? Both your code and mine will run forever.

function peanoAddition(x, y) {
  if (y === 0) {
    return x;
  }
  return peanoAddition(x + 1, y - 1);
}