24.Example programs using Recursion

1.Print the factorial of a number using recursion
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)

n=int(input('Enter n..:'))
x=fact(n)
print("factorial of ..",n ," ..is.. ",x)

output:
Enter n..:5
factorial of .. 5  ..is....120

2.Program to print n’th Fibonacci number
def fib(n):
  if n <= 1:
      return n
  else:
     return fib(n-1) + fib(n-2)

n=int(input('Enter n…'))
x=fib(n)
print (n,"th Fibonacci number is...",x)

output:
Enter n…5
5 th Fibonacci number is... 5

3.Program to find sum of the digits of a number
def sumd(n):
    if n == 0:
        return 0
    else:
        return n%10 + sumd(n//10)
n=int(input('Enter n'))
s=sumd(n)
print ("sum of the digits of ..",n ," ..is.. ",s)

output:
Enter n...123
sum of the digits of .. 123  ..is..  6

4.Program to convert decimal number to binary using recursion
def decb(n):
    if n==0:
        return 0
    else:
        return n%2 + 10* decb(n//2)
n=int(input('Enter n.:'))
b=decb(n)
print("The binary equivalent of ..",n ," ..is.. ",b)

output
Enter n.:12
The binary equivalent of .. 12  ..is..  1100

5.Program to find sum of n natural numbers using recursion
def sum(n):
    if n ==0:
        return 0
    else:
        return n + sum(n-1)

n=int(input('Enter n..'))
s=sum(n)
print("The sum of natural numbers up to ...",n ," ..is.. ",s)

output
Enter n..10
The sum of natural numbers up to ... 10  ..is..  55

6.Program to find nPr using a recursive factorial function
def fact(n):
  if n==0:
    return 1
 else:
    return n*fact(n-1)
n=int(input('Enter n..'))
r=int(input('Enter r..'))
print("nPr=", fact(n)//fact(n-r))

output
Enter n..5
Enter r..3
nPr= 60

7.GCD of two numbers using recursion ( university question)
def gcd_recursive(a, b):
    if b == 0:
        return a
    else:
        return gcd_recursive(b, a % b)

x=int(input('Enter x='))
y=int(input('Enter y='))
gcd=gcd_recursive(x,y)
print(f'gcd of {x} and {y} is={gcd}')

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators