Last active
October 12, 2021 21:50
-
-
Save msyvr/7bae8da60681ce255d1f3f0182707d8f to your computer and use it in GitHub Desktop.
mit 6.0001 recursion - multiplication and factorial implemented via recursion (vs built in '*' or 'math.factorial()')
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
def mult_rec(x, y): | |
if y == 1: | |
return x | |
else: | |
return x + mult_rec(x, y-1) | |
def fact_rec(x): | |
if x == 1: | |
return x | |
elif x > 1: | |
return x * fact_rec(x-1) | |
else: | |
print('x must be int >= 1') | |
if __name__ == "__main__": | |
choice = input('(m)ultiplication or (f)actorial?: ').lower() | |
if choice == 'm': | |
x = int(input('x: ')) | |
y = int(input('y: ')) | |
print(mult_rec(x,y)) | |
elif choice == 'f': | |
x = int(input('x: ')) | |
print(fact_rec(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment