1. PRINT 1 to 5
PYTHON CODE:
def fact(i):
if i<=5:
print(i)
i+=1
fact(i)
fact(1)
๐ Simple Flow
fact(1)
โ print 1
โ fact(2)
fact(2)
โ print 2
โ fact(3)
fact(3)
โ print 3
โ fact(4)
fact(4)
โ print 4
โ fact(5)
fact(5)
โ print 5
โ fact(6)
fact(6)
โ stop โ`
๐งพ Output
1
2
3
4
5
2. ODD NUMBERS PRINT: 1 3 5 7
PYHTON CODE :
def fact(i):
if i<=15:
if i%2!=0:
print(i)
i+=1
fact(i)
fact(1)
๐ Simple Flow
fact(1)
โ 1 is odd โ print 1
โ call fact(2)
fact(2)
โ not odd โ
โ call fact(3)
fact(3)
โ print 3
โ call fact(4)
fact(4)
โ skip
โ call fact(5)
...
๐ continues same until 15
fact(15)
โ print 15
โ call fact(16)
fact(16)
โ stop โ
๐งพ Output
1 3 5 7 9 11 13 15
3. FACTORIAL :
Factorial meaning:
5! = 5 ร 4 ร 3 ร 2 ร 1 = 120
PYHTON CODE :
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
๐ Simple Flow
factorial(5)
โ 5 * factorial(4)
factorial(4)
โ 4 * factorial(3)
factorial(3)
โ 3 * factorial(2)
factorial(2)
โ 2 * factorial(1)
factorial(1)
โ return 1 โ
(stop)
๐ Backward Calculation
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
๐งพ Output
120
4. SUM OF N NUMBERS
โ What this code does
๐ Finds sum of first n numbers
5 โ 1 + 2 + 3 + 4 + 5 = 15
PYHTON CODE :
python
def SUM(n):
if n == 1:
return 1
return n + SUM(n - 1)
print(SUM(5))
๐ Simple Flow
SUM(5)
โ 5 + SUM(4)
SUM(4)
โ 4 + SUM(3)
SUM(3)
โ 3 + SUM(2)
SUM(2)
โ 2 + SUM(1)
SUM(1)
โ return 1 โ
(stop)
๐ Backward Calculation
SUM(2) = 2 + 1 = 3
SUM(3) = 3 + 3 = 6
SUM(4) = 4 + 6 = 10
SUM(5) = 5 + 10 = 15
๐งพ Output
15
5. COUNT DIVISORS
โ What this code does
๐ Counts how many numbers divide num (except 1 and itself)
For 100:
๐ Divisors = 2, 4, 5, 10, 20, 25, 50
๐ Count = 7
PYHTON CODE :
python
def count_divisors(num, div=2, count=0):
if div > num // 2:
return count
if num % div == 0:
count += 1
return count_divisors(num, div + 1, count)
print(count_divisors(100))
๐ How it Works
For num = 100:
- Start
div = 2 - If divisible โ
increase count - Call function again with
div + 1 - Stops when
div > 50
6. prime check
PYHTON CODE :
`python
def is_prime(num, div=2):
if div > num // 2:
return True
if num % div == 0:
return False
return is_prime(num, div + 1)
num = int(input("enter a number: "))
if num > 1 and is_prime(num):
print("This number is Prime")
else:
print("This number is not Prime")
`
๐ How It Works (Simple)
- Start checking from
div = 2 - If divisible โ โ Not Prime
- Else โ call function with
div + 1 - Stops when
div > num/2โ โ Prime
7. GCD
PYHTON CODE :
`python
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(10, 50))
`
๐ฅ Short Flow
gcd(10,50)
โ gcd(50,10)
โ gcd(10,0)
โ 10
Top comments (1)
Good one, check python spelling