DEV Community

Divya Divya
Divya Divya

Posted on

Recursion?

1. 1 2 3 4 5:
Python

def print_numbers(n):
    if n > 5:  
      print(n)
      print_numbers(n + 1)   

print_numbers(1)
Enter fullscreen mode Exit fullscreen mode

2. Sum of Numbers:
Python

def sum_numbers(n):
    if n == 0:        
        return 0

    return n + sum_numbers(n - 1)

print(sum_numbers(5))   

Enter fullscreen mode Exit fullscreen mode

3. LCM:
Python

def lcm(a, b, current=None):
    if current is None:
        current = max(a, b)

    if current % a == 0 and current % b == 0:
        return current

    return lcm(a, b, current + 1)

print(lcm(12, 18))    
Enter fullscreen mode Exit fullscreen mode

4. Factorial:
Python

def factorial(n):
    if n == 0 or n == 1:  
        return 1

    return n * factorial(n - 1)

print(factorial(5))   
Enter fullscreen mode Exit fullscreen mode

5. Odd Numbers:
Java

class Main {
    static void printOdd(int n) {
        if (n > 10) {   
            return;
        }

        if (n % 2 != 0) {
            System.out.println(n);
        }

        printOdd(n + 1);   
    }

    public static void main(String[] args) {
        printOdd(1);
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Prime Numbers:
Python

def is_prime(n, i=2):
    if n <= 1:
        return False

    if i * i > n:  
        return True

    if n % i == 0:
        return False

    return is_prime(n, i + 1)


print(is_prime(7))   
print(is_prime(10)) 
Enter fullscreen mode Exit fullscreen mode

7. GCD:
Python

def gcd(a, b):
    if b == 0:     
        return a
    return gcd(b, a % b)

print(gcd(12, 18))   

Enter fullscreen mode Exit fullscreen mode

Top comments (0)