Implement numeric sum only with successor and predecessor

-2

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

    
asked by anonymous 24.04.2018 / 01:58

1 answer

2

To simplify the answer, I will only consider that the entries will be nonnegative integers. It is given that there are two operators in the numerical system used 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, it would look like:

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

To not break the spell, I implemented it in Python just to show 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 at Repl.it | Ideone | GitHub GIST

As for the C implementation, I believe you can do something on your own, but anything, feel free to ask.

    
24.04.2018 / 02:48