تمرین‌ها

تمرین ۷:

!n در پایتون با الگوریتم بازگشتی

برنامه‌ای به زبان پایتون بنویسید که فاکتوریل عدد طبیعی n یعنی !n را با الگوریتم بازگشتی محاسبه کند.

کد:
def Fact(x):
    r = 0
    if x == 0 or x == 1:
        r = 1
    else:
        r = x * Fact(x-1)
    return r

def Main(): print("n! through Recursive Algorithm") print("To exit the program, enter a negative integer!") print("-------------------------------------- \n") while True: try: n = int(input("n = ")) if n<0: print("The program is terminated. Bye!") break else: print(n,"! = ", Fact(n), sep="", end="\n\n") except: print("Error: Maximum Recursion Depth! \n")
Main()

اجرا:
================= RESTART: C:\n! Recursive.py =================
pythonize.ir 	 programmer: Mohammad Rajabpur 

------------------------------------------------
n! through Recursive Algorithm
To exit the program, enter a negative integer!
------------------------------------------------ 

n = 1
1! = 1

n = 2
2! = 2

n = 3
3! = 6

n = 4
4! = 24

n = 5
5! = 120

n = 6
6! = 720

n = 10
10! = 3628800

n = 20
20! = 2432902008176640000

n = 30
30! = 265252859812191058636308480000000

n = 40
40! = 815915283247897734345611269596115894272000000000

n = 50
50! = 30414093201713378043612608166064768844377641568960512000000000000

n = -1
The program is terminated. Bye!