Python3 Program To Add Two Numbers
Python3 Program To Add Two Numbers
num1 = 15
num2 = 12
# Adding two nos
Output:
Sum of 15 and 12 is 27
number1 = input("First number: ")
Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Python Program for factorial of a number
Factorial of a non-negative integer, is multiplication of all integers
smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1
which is 720.
Recursive Solution:
Factorial can be calculated using following recursive formula.
n! = n * (n-1)!
n! = 1 if n = 0 or n = 1
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num = 5;
Iterative Solution:
Factorial can also be calculated iteratively as
recursion can be costly for large numbers. Here we have shown
the iterative approach using both for and while loop.
def factorial(n):
res = 1
for i in range(2, n+1):
res *= i
return res
num = 5;
Output :
Factorial of 5 is 120
Using While loop
# Function to find factorial of given number
def factorial(n):
if(n == 0):
return 1
i = n
fact = 1
while(n / i != n):
fact = fact * i
i -= 1
return fact
# Driver Code
num = 5;
Output :
Factorial of 5 is 120
Time complexity of the above iterative solutions is O(n).
def factorial(n):
# single line to find factorial
return 1 if (n == 1 or n == 0) else n * factorial(n - 1)
# Driver Code
num = 5
print ("Factorial of", num, "is", factorial(num))
Output:
Factorial of 5 is 120
The above solutions cause overflow for small numbers. Please refer factorial of large
number for a solution that works for large numbers.