Implement numerical sum with successor and predecessor only

Asked

Viewed 817 times

-2

Consider a numerical system that does not have the addition operation implemented and that you have only operators (functions) successor and predecessor. Then, it is asked to write a function recursive that calculates the sum of two numbers x and y through these two operators: successor and predecessor.

  • And what exactly do you want? An explanation of who is successor and predecessor?

  • I already know, but I don’t know how to solve the problem, I can’t even think of a way

1 answer

2

To simplify the answer, I will only consider that entries will be non-negative integers. It is given that there are two operators in the used numerical system where I will represent as x+ the successor operator and x- the predecessor. You are asked to implement a recursive function that returns the sum of two numbers. The logic to be implemented is: increment one of the values while the other is decremented, while the other (which is reducing) does not reach zero; when it arrives, stop the recursion. So, in a pseudo-language I just invented, I’d be:

function sum(x: int, y: int): int
    if y = 0:
        return x
    return sum(x+, y-)

To not break the magic, I implemented in Python just to show that it works:

sucessor = lambda x: x+1
antecessor = lambda x: x-1

def sum(x, y):
    if not y:
        return x
    return sum(sucessor(x), antecessor(y))

print(sum(3, 5))  # 8

See working on Repl.it | Ideone | Github GIST

As for the implementation in C, I believe that with this you can already elaborate something on your own, but, anything, feel free to question.

  • now yes, thank you very much, it helped a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.