Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Q*:Write a Python program to solve the Fibonacci sequence using

recursion.
1,1,2,3,5,8,13,21,34,55,89….
Ex:
fibonacci(7)->13
fibonacci(10)->55

********************************************************************************
Q1 : Write a Python program to get the sum of a non-negative integer.

Ex:
sumDigits(345) -> 12
sumDigits(45) -> 9
Sol:
def sumDigits(n):
if n == 0:
return 0
else:
return n % 10 + sumDigits(int(n / 10))

print(sumDigits(345))
print(sumDigits(45))
********************************************************************************

Q2.Write a Python program to calculate the harmonic sum of n-1.


Note: The harmonic sum is the sum of reciprocals of the positive integers.
Ex :

harmonic_sum(7)->2.5928571428571425
harmonic_sum(4)->2.083333333333333
Sol:
def harmonic_sum(n):
if n < 2:
return 1
else:
return 1 / n + (harmonic_sum(n - 1))

print(harmonic_sum(7))
print(harmonic_sum(4))
********************************************************************************

Q3: Write a Python program to calculate the value of 'a' to the power 'b'.
Ex:
power(3,4) -> 81
power(100,0) -> 1

Sol:
def power(a,b):
if b==0:
return 1
elif a==0:
return 0
elif b==1:
return a
else:
return a*power(a,b-1)

print(power(3,4))
********************************************************************************

Q4:Write a Python program to find the greatest common divisor (gcd) of


two integers.

Ex:
Recurgcd(12,14)->2
Recurgcd(21,11)->1
Sol:
def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)

if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
print(Recurgcd(12,14))

********************************************************************************

Q:Write a Python program to calculate the sum of the positive integers of


n+(n-2)+(n-4)... (until n-x =< 0).
Ex:
sum_series(6) -> 12
My method:
sum_series(10) -> 30
def sum_series(n):
Sol: if n<=0:
def sum_series(n): return 0
if n < 1: else:
return 0 return n + sum_series(n-2)
print(sum_series(1))
else:
return n + sum_series(n - 2)

print(sum_series(6))
print(sum_series(10))

*********************************************************************************

You might also like