Skip to content

Instantly share code, notes, and snippets.

@tevino
Created June 6, 2020 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tevino/8de206a97a3147e05edfe68eb391da23 to your computer and use it in GitHub Desktop.
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.
# 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