21BCE9371-CSE-LAB-01 Reference

You might also like

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

NAME :- UDAY SAI MANOJ

REG NO :- 21BC39371
Experiment -1 :- Introduction to Algorithm
Analysis
1. Write a Program to find the factorial of
a given number using recursion and
analyze the time complexity.

CODE:-

import java.util.*;
public class lab251 {
//21BCE9371
//UDAY SAI MANOJ

static long fac(long a) {


if(a==0) {
return 1;
}
else {
return(a*fac(a-1));
}

public static void main(String[]


args) {
// TODO Auto-generated method
stub
long startTime;
long endTime;
long elapsedTime;

startTime = System.nanoTime();

Scanner uday=new
Scanner(System.in);
System.out.println("Enter
Number:");
int num=uday.nextInt();
long fact=fac(num);
System.out.println("Factorial
of "+num+" is "+fact);

endTime = System.nanoTime();

elapsedTime = endTime -
startTime;

System.out.println();
System.out.println("Time
Taken(Time complexity): " +
elapsedTime +" ns");
}

OUTPUT:-
Analyzis:-
2. Write a Program to find the transpose
of a given matrix and display its time
complexity.

CODE:-

public class lab252 {

public static void main(String[]


args) {

long startTime;
long endTime;
long elapsedTime;

startTime = System.nanoTime();

int[][] uday=
{{1,3,6},{2,4,7},{9,8,5}};

System.out.println("Transpose
Of The Matrix:\n");

for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(uday[i][j]+" ");
}
System.out.println();
}

endTime = System.nanoTime();

elapsedTime = endTime -
startTime;

System.out.println();
System.out.println("Time
Taken(Time complexity): " +
elapsedTime +" ns");
}

OUTPUT:-
Analyzis:-
3. Write a Program to illustrate the
difference between recursion and
iteration by giving its time complexities.

CODE:-

import java.util.Scanner;

public class lab253 {


static long fac(long a) {
if(a==0) {
return 1;
}
else {
return(a*fac(a-1));
}

static long factorial(int n){


long fact = 1;

for (int i = 1; i <= n;


i++) {
fact = fact * i;
}

return fact;
}

public static void main(String[]


args) {

long startTime;
long endTime;
long elapsedTime;

long startTime1;
long endTime1;
long elapsedTime1;

startTime = System.nanoTime();

Scanner uday=new
Scanner(System.in);
System.out.println("Enter
Number:");

int num=uday.nextInt();
long fact=fac(num);
System.out.println("The
Factorial of "+num+" is
(Recursive):"+fact);
endTime = System.nanoTime();

elapsedTime = endTime -
startTime;

System.out.println("Time Taken
in Recursive Method: " +
elapsedTime+" ns");

startTime1 = System.nanoTime();
System.out.println("\nThe
Factorial of " + num + " is
(Iterative):" + factorial(num));
endTime1 = System.nanoTime();

elapsedTime1 = endTime1 -
startTime1;
System.out.println("Time Taken
in Iterative Method :" +
elapsedTime1 +" ns");
int diff=(int) (elapsedTime1-
elapsedTime);

System.out.println("\nDifference
between recursion and iteration by
giving its time complexities:
"+diff);
}

}
OUTPUT:-

Analyzis:-

You might also like