Created
June 6, 2020 06:38
-
-
Save tevino/8de206a97a3147e05edfe68eb391da23 to your computer and use it in GitHub Desktop.
A way of implementing subtraction using addition only. Available operations: loop, assign, add by one. Restrictions: no negative numbers, integers only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A way of implementing subtraction using addition only. | |
# Available operations: loop, assign, add by one. | |
# Restrictions: no negative numbers, integers only. | |
# | |
# Aadit M Shah on StackOverflow says this method was devised by Stephen Cole Kleene, but I can't find any sources. | |
# https://stackoverflow.com/a/34079075 | |
def subtract(minuend, subtrahend): | |
for _ in range(subtrahend): | |
minuend = _subtract_by_one(minuend) | |
return minuend | |
def _subtract_by_one(n): | |
difference = 0 | |
difference_plus_one = 0 | |
for _ in range(n): | |
difference = difference_plus_one | |
difference_plus_one += 1 | |
return difference | |
if __name__ == '__main__': | |
from random import randint | |
for _ in range(10): | |
a = randint(0, 999) | |
b = randint(0, a) | |
print('{0:>3} - {1:>3} = {2:>3} got {3:>3}'.format(a, b, a - b, subtract(a, b))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment