简体   繁体   中英

Add any two numbers recursively in JavaScript

I'm trying to add two numbers using recursion in JavaScript. So far I've come up with

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

It works with all positive numbers, however, not for negative integers. I get a Max call stack size exceeded error.

I've searched for a simple recursive function in Js but have only found them in C and other languages I'm not too familiar. I've found one for Fibonacci and numbers in an Array, but I just want any two numbers, not an array.

Since this is, presumably, homework, let me just give a hint instead of spoon-feeding you the code:

Instead of simply checking for y != 0 , try checking for y < 0 and y > 0 . You should be able to figure out how to handle each of these two cases in such a way that you'll, eventually, arrive at y == 0 .


Ps. Of course, even with the extension I suggested above, your method will still only work for integers. If you really want to make it work for arbitrary floats, perhaps the simplest solution would be something like:

if (y > 0 && y < 1) {
    return sum(2*x, 2*y) / 2;
}

The reason this trick works at all is that JavaScript floats are binary, and thus can only exactly represent numbers of the form n / 2 k , where n and k are integers. Thus, repeatedly multiplying any (finite) number by 2 in JavaScript will eventually yield an integer.

Of course, it seems kind of silly to use multiplication and division in order to implement addition, but at least we could, in principle, replace them with simple bit shifts — that is, we could, if bit shifts worked on floats in JavaScript, which, alas, they don't.

If the y value is initially negative the recursion wouldn't stop because of your conditional statement. Why not have an if statement that checks if the y Val is greater or less than 0. Then you can decrement y if y is greater than 0 or increment if y is less than 0(to obtain the same effect you would need to decrement x in the case of y <0). Thus the recursion would stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM