Tuesday, March 24, 2015

Recursive methods in java

Recursion:

Recursion is a programming technique that allows the programmer to express operations in terms of themselves.


Recursive method to find the factorial of the number

public static int factorial(int num) {
          if (num == 0 || num == 1)
                   return 1;
          else
                   return num * factorial(num - 1);
}

Recursive method to find the sum of first N natural numbers

public static int sumofNnumber(int N) {
          if (N == 1)
                   return 1;
          else
                   return N + sumofNnumber(N - 1);
}




Recursive method to find the GCD of two numbers

public static int gcdOfNumbers(int num1, int num2) {
          if (num1 == num2)
                   return num1;
          else if (num1 > num2)
                   return gcdOfNumbers(num1 - num2, num2);
          else
                   return gcdOfNumbers(num1, num2 - num1);
}

Recursive method to multiply two numbers using Russian Peasant algorithm

public static int russianPeasantMultiply(int num1, int num2) {
          if (num1 == 1)
                   return num2;
                   else if (num1 % 2 == 1)
                             return num2 + russianPeasantMultiply(num1 / 2, num2 * 2);
                    else
                             return russianPeasantMultiply(num1 / 2, num2 * 2);

}

Recursive method to find the M^N

public static int power(int m, int n) {
                   if (n == 1)
                             return m;
                   else
                             return m * power(m, n - 1);
}

Recursion method to find the reverse of the given number

public static long reverse(long num){
          return reverse(num,0);
}
private static long reverse(long n, long m) {
          if (n == 0)
                   return m;
          else
                   return reverse(n / 10, m * 10 + n % 10);
}



No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...