In: Computer Science
1. Implement the recursive factorial function given below (from the lecture notes on recursion). Develop a main program that allows the user to enter any integer (positive) integer value, and displays the factorial of that value. The program should allow the user to either keep entering another value, or quit the program. public static int factorial(int n) { if (n == 0 || n == 1) return (1); else return (n * factorial(n-1)); } 2. Determine the largest value for n that can be correctly computed. 3. Implement the recursive Towers of Hanoi function given below (from the lecture notes). Develop a main program that allows the user to enter any number of disks to solve. public static void towers(int numDisks, String startPeg, String destPeg, String sparePeg) { if (numDisks == 1) System.out.println("Move disk from " + startPeg + " to " + destPeg); else { towers(numDisks-1, startPeg, sparePeg, destPeg); System.out.println("Move disk from " + startPeg + " to " + destPeg); towers(numDisks-1, sparePeg, destPeg, startPeg); } } 4. Modify function towers so that all the print statements are disabled (i.e., comment them out). There needs to be a statement after if(numDisks …), so replace that with just numDisks = numDisks. (The compiler will actually remove this pointless statement.) Modify the main program so that “Starting towers …” is displayed right before the function is called, and “Finished towers” when completed (right after the function call). Run your program using this new version of the function (that does not display the moves) to determine how long it takes to complete for the following number of disks: 10, 20, 30, 32, 34, 36. Use your smart phone to determine each execution time to the nearest second. use java
Factorial Program using Recursion:
class FactorialExample{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Towers of hanio:
import java.util.*;
class GFG
{
// Java recursive function to solve tower of hanoi puzzle
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
// Driver method
public static void main(String args[])
{
int n ; // Number of disks
Scanner sc = new Scanner(System.in);
System.out.println("Enter no.of disks");
n = sc.next();
towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods
}
}