0% found this document useful (0 votes)
3 views13 pages

Rohit 202100252

Uploaded by

rohitm04122002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Rohit 202100252

Uploaded by

rohitm04122002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

LAB 7

Aim: Write a java program to find factorial using Direct and Tail recursion and check execution time and
performance time complexity using Big O Notation.

Theory: Direct recursion is the type of recursion in which a function directly calls itself within its own block of
code. If a recursive function calling itself and that recursive call is the last statement in the function then it’s
known as Tail Recursion.

Algorithm:

Step 1: Start.

Step 2: Declare a variable ‘number’ and assign a value to it.

Step 3: Call the ‘findFactorialDirect’ function with ‘number’ as argument.

Step 4: Call the ‘findFactorialTail’ function with ‘number’ as argument.

Step 5: Print the execution time of both functions.

Step 6: Define ‘findFactorialDirect’ function:

if (n == 0 || n == 1)

return 1

else

return n * findFactorialDirect (n – 1)

Step 7: Define ‘findFactorialTail’ function:

if (n == 0 || n == 1)

return result

else

return n * findFactorialTail (n – 1, n * result)

Step 8: End.

Source Code:

public class Factorial {

public static void main(String[] args) {

int number = 8;

long startTime = System.nanoTime();

long factorialDirect = findFactorialDirect(number);

long endTime = System.nanoTime();

long directTime = endTime - startTime;

startTime = System.nanoTime();

long factorialTail = findFactorialTail(number,1);

endTime = System.nanoTime();

long tailTime = endTime - startTime;

ROHIT_202100252
System.out.println("Factorial of " + number + " using direct recursion is: " + factorialDirect);

System.out.println("Execution time of direct recursion: " + directTime + " nanoseconds");

System.out.println("\nFactorial of " + number + " using tail recursion is: " + factorialTail);

System.out.println("Execution time of tail recursion: " + tailTime + " nanoseconds");

public static long findFactorialDirect(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * findFactorialDirect(n - 1);

public static long findFactorialTail(int n, long result) {

if (n == 0 || n == 1)

return result;

else

return findFactorialTail(n - 1, n * result);

Output:

Factorial of 8 using direct recursion is: 40320

Execution time of direct recursion: 2400 nanoseconds

Factorial of 8 using tail recursion is: 40320

Execution time of tail recursion: 1500 nanoseconds

ROHIT_202100252
Aim: Write a java program to determine a factorial of a large number by incorporating BigInteger class
available in MATH API.

Theory: BigInteger class is used for the mathematical operation which involves very big integer calculations
that are outside the limit of all available primitive data types. In this way, BigInteger class is very handy to use
because of its large method library and it is also used a lot in competitive programming.

Algorithm:

Step 1: Start

Step 2: Call the ‘calculateFactorial’ function with ‘n’ as argument.

Step 3: Print the calculated factorial.

Step 4: Define ‘calculateFactorial’ function

Step 5: End.

Source Code:

import java.math.BigInteger;

import java.util.Scanner;

public class FactorialCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to calculate its factorial: ");

int n = scanner.nextInt();

BigInteger factorial = calculateFactorial(n);

System.out.println("Factorial of " + n + " is: " + factorial);

scanner.close();

public static BigInteger calculateFactorial(int n) {

BigInteger result = BigInteger.ONE;

for (int i = 2; i <= n; i++) {

result = result.multiply(BigInteger.valueOf(i));

return result;

Output:

Enter a number to calculate its factorial: 15 Factorial of 15 is: 1307674368000

ROHIT_202100252
Aim: Write a java program to compute Fibonacci numbers using Direct Method & Dynamic Programming.

Theory: The direct method in Java is a method that is invoked directly, without the use of a virtual machine.
This is in contrast to virtual methods, which are invoked indirectly, through the use of a virtual machine.
Dynamic Programming is a method used in mathematics and computer science to solve complex problems by
breaking them down into simpler subproblems. By solving each subproblem only once and storing the
results, it avoids redundant computations, leading to more efficient solutions for a wide range of problems.

Algorithm:

Step 1: Start.

Step 2: Create a public class ‘Fibonacci’.

Step 3: Define ‘fibonacciRecurive’ function, ‘fibonacciDynamic’ function and


‘fibonacciDynamicHelper’ function.

Step 4: Calculate the Fibonacci series and display the output.

Step 5: End.

Source Code:

import java.util.Scanner;

import java.util.HashMap;

public class Fibonacci {

public static int fibonacciRecursive(int n) {

if (n <= 1)

return n;

return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);

public static int fibonacciDynamic(int n) {

HashMap<Integer, Integer> memo = new HashMap<>();

memo.put(0, 0);

memo.put(1, 1);

return fibonacciDynamicHelper(n, memo);

private static int fibonacciDynamicHelper(int n, HashMap<Integer, Integer> memo) {

if (memo.containsKey(n))

return memo.get(n);

int result = fibonacciDynamicHelper(n - 1, memo) + fibonacciDynamicHelper(n - 2, memo);

memo.put(n, result);

return result;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

ROHIT_202100252
System.out.print("Enter the value of n: ");

int n = scanner.nextInt();

scanner.close();

long startRecursive = System.currentTimeMillis();

int fibRecursive = fibonacciRecursive(n);

long endRecursive = System.currentTimeMillis();

System.out.println("Fibonacci using Direct Recursion: " + fibRecursive);

System.out.println("Time taken (ms) for Direct Recursion: " + (endRecursive - startRecursive));

long startDynamic = System.currentTimeMillis();

int fibDynamic = fibonacciDynamic(n);

long endDynamic = System.currentTimeMillis();

System.out.println("Fibonacci using Dynamic Programming: " + fibDynamic);

System.out.println("Time taken (ms) for Dynamic Programming: " + (endDynamic - startDynamic));

Output:

Enter the value of n: 10

Fibonacci using Direct Recursion: 55

Time taken (ms) for Direct Recursion: 0

Fibonacci using Dynamic Programming: 55

Time taken (ms) for Dynamic Programming: 0

ROHIT_202100252
Aim: Write a java program to implement palindrome checking and selection sort recursively.

Theory: Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the
smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the
list. The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and
swaps it with the first element of the unsorted part. This process is repeated for the remaining unsorted
portion until the entire list is sorted.

Algorithm:

Step 1: Start.

Step 2: Create a public class ‘RecursiveDemo’.

Step 3: Define the necessary functions.

Step 4: Calculate and display the output.

Step 5: End.

Source Code:

import java.util.Scanner;

public class RecursiveDemo {

public static boolean isPalindrome(String str) {

return isPalindromeHelper(str, 0, str.length() - 1);

private static boolean isPalindromeHelper(String str, int start, int end) {

if (start >= end) {

return true;

if (str.charAt(start) != str.charAt(end)) {

return false;

return isPalindromeHelper(str, start + 1, end - 1);

public static void recursiveSelectionSort(int[] arr) {

recursiveSelectionSortHelper(arr, 0);

private static void recursiveSelectionSortHelper(int[] arr, int start) {

if (start < arr.length - 1) {

int minIndex = start;

for (int i = start + 1; i < arr.length; i++) {

if (arr[i] < arr[minIndex]) {

minIndex = i;

ROHIT_202100252
}

int temp = arr[start];

arr[start] = arr[minIndex];

arr[minIndex] = temp;

recursiveSelectionSortHelper(arr, start + 1);

public static void recursiveQuickSort(int[] arr) {

recursiveQuickSortHelper(arr, 0, arr.length - 1);

private static void recursiveQuickSortHelper(int[] arr, int low, int high) {

if (low < high) {

int partitionIndex = partition(arr, low, high);

recursiveQuickSortHelper(arr, low, partitionIndex - 1);

recursiveQuickSortHelper(arr, partitionIndex + 1, high);

private static int partition(int[] arr, int low, int high) {

int pivot = arr[high];

int i = low - 1;

for (int j = low; j < high; j++) {

if (arr[j] < pivot) {

i++;

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;

return i + 1;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

ROHIT_202100252
System.out.print("Enter a string to check if it's a palindrome: ");

String inputString = scanner.nextLine();

if (isPalindrome(inputString)) {

System.out.println(inputString + " is a palindrome.");

} else {

System.out.println(inputString + " is not a palindrome.");

System.out.print("Enter the size of the array for selection sort: ");

int size = scanner.nextInt();

int[] selectionArray = new int[size];

System.out.println("Enter the elements of the array:");

for (int i = 0; i < size; i++) {

selectionArray[i] = scanner.nextInt();

recursiveSelectionSort(selectionArray);

System.out.println("Array after selection sort:");

for (int num : selectionArray) {

System.out.print(num + " ");

System.out.println();

System.out.print("Enter the size of the array for quick sort: ");

size = scanner.nextInt();

int[] quickArray = new int[size];

System.out.println("Enter the elements of the array:");

for (int i = 0; i < size; i++) {

quickArray[i] = scanner.nextInt();

recursiveQuickSort(quickArray);

System.out.println("Array after quick sort:");

for (int num : quickArray) {

System.out.print(num + " ");

System.out.println();

scanner.close();

ROHIT_202100252
}

Output:

Enter a string to check if it's a palindrome: deed

deed is a palindrome.

Enter the size of the array for selection sort: 6

Enter the elements of the array:

23

46

64

12

87

Array after selection sort:

5 12 23 46 64 87

Enter the size of the array for quick sort: 4

Enter the elements of the array:

30

79

21

Array after quick sort:

4 21 30 79

ROHIT_202100252
Aim: Write a java program to compute the greatest common divisor (GCD) using recursion.

Theory: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest
number that divides both of them.

Algorithm:

Step 1: Start.

Step 2: Create a public class ‘GCD’.

Step 3: Define ‘findGCD’ function.

Step 4: Prompt the user to enter two numbers to calculate GCD.

Step 5: Display the output.

Step 6: End.

Source Code:

import java.util.Scanner;

public class GCD {

public static int findGCD(int num1, int num2) {

if (num2 == 0) {

return num1;

} else {

return findGCD(num2, num1 % num2);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");

int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");

int num2 = scanner.nextInt();

scanner.close();

System.out.println("GCD of " + num1 + " and " + num2 + " is: " + findGCD(num1, num2));

Output:

Enter the first number: 48

Enter the second number: 18

GCD of 48 and 18 is: 6

ROHIT_202100252
Aim: Write a java program to implement recursive methods to compute mathematical series.

Source Code:

import java.util.Scanner;

public class RecursiveMethods {

public static void displayDigitsReverse(int number) {

if (number == 0) {

return;

System.out.print(number % 10);

displayDigitsReverse(number / 10);

public static void displayStringReverse(String str) {

if (str.isEmpty()) {

return;

System.out.print(str.charAt(str.length() - 1));

displayStringReverse(str.substring(0, str.length() - 1));

public static int countOccurrences(String str, char ch) {

if (str.isEmpty()) {

return 0;

if (str.charAt(0) == ch) {

return 1 + countOccurrences(str.substring(1), ch);

} else {

return countOccurrences(str.substring(1), ch);

public static int binarySearch(int[] arr, int target, int low, int high) {

if (low > high) {

return -1;

int mid = (low + high) / 2;

if (arr[mid] == target) {

return mid; // element found

ROHIT_202100252
} else if (arr[mid] < target) {

return binarySearch(arr, target, mid + 1, high);

} else {

return binarySearch(arr, target, low, mid - 1);

public static double computeSeries(int i) {

if (i == 0) {

return 1;

return computeSeries(i - 1) + 1.0 / Math.pow(2, i);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer to display its digits in reverse order: ");

int num = scanner.nextInt();

System.out.print("Digits in reverse order: ");

displayDigitsReverse(num);

System.out.println();

System.out.print("Enter a string to display it in reverse order: ");

scanner.nextLine();

String str = scanner.nextLine();

System.out.print("String in reverse order: ");

displayStringReverse(str);

System.out.println();

System.out.print("Enter a string: ");

str = scanner.nextLine();

System.out.print("Enter a character to find its occurrences: ");

char ch = scanner.next().charAt(0);

int occurrences = countOccurrences(str, ch);

System.out.println("Occurrences of '" + ch + "' in '" + str + "': " + occurrences);

System.out.print("Enter the length of the array: ");

int length = scanner.nextInt();

int[] arr = new int[length];

ROHIT_202100252
System.out.print("Enter " + length + " elements in sorted order: ");

for (int i = 0; i < length; i++) {

arr[i] = scanner.nextInt();

System.out.print("Enter the element to search: ");

int target = scanner.nextInt();

int index = binarySearch(arr, target, 0, arr.length - 1);

if (index != -1) {

System.out.println("Element found at index: " + index);

} else {

System.out.println("Element not found in the array.");

System.out.print("Enter the value of i to compute the series m(i): ");

int seriesIndex = scanner.nextInt();

System.out.println("m(" + seriesIndex + ") = " + computeSeries(seriesIndex));

scanner.close();

Output:

Enter an integer to display its digits in reverse order: 645

Digits in reverse order: 546

Enter a string to display it in reverse order: bye

String in reverse order: eyb

Enter a string: itlab

Enter a character to find its occurrences: t

Occurrences of 't' in 'itlab': 1

Enter the length of the array: 4

Enter 4 elements in sorted order: 12

23

34

49

Enter the element to search: 22

Element not found in the array.

Enter the value of i to compute the series m(i): 1

m(1) = 1.5

ROHIT_202100252

You might also like