I need to write a recursive function that can add two numbers (x, y), assuming y is not negative. I need to do it using two functions which return x-1 and x+1, and I can't use + or - anywhere in the code. I have no idea how to start, any hints?
![]() ![]() ![]() |
Lets say that
Then, (in pseudocode)
Observe, this only works for non-negative y. |
||||
|
![]() ![]() |
Big hint: you're describing Peano arithmetic. |
||
|
![]() ![]() |
In a comment the OP says:
You can try upping the recursion limit with sys.recursionlimit (after an Alternatively, you may have miscoded the "base-recursion guard" which is supposed to return without further recursion when |
||
|
![]() ![]() |
pseudo-code :
where f(x) is your function that returns x+1 or, if you can't do a for loop because that requires +s :
where f(x) is the function that gives x+1 and g(y) is the function that gives y-1 |
||||
|
![]() ![]() |
This sounds like homework. So this is probably cheating:
So you can easily add or subtract two numbers without using +/-. No need for any recursion. |
|||
|
log(exp(x)*exp(y))
is against the rules too, eh? – Daniel Stutzbach 2 days ago