Please kindly choose one of the answer and explain how the code process to get t
ID: 3871191 • Letter: P
Question
Please kindly choose one of the answer and explain how the code process to get the answer. Thanks
1. How many times is the factorial method in the following code invoked for factorial(6)?
public static long factorial(int n){
if(n==1)
return 1;
else
return n*factorial(n-1);
}
a.4
b.5
c.6
d.7
e.None of the above
2. How many times is the fib method in the following code invoked for fib(5)?
public static long fib(int n){
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fib(n-1) + fib(n-2);
}
a.10
b.12
c.14
d.15
e.17
h.18
i.None of the above
3.How many times is the isPal method in the following code invoked for isPal("abcdeghiktkihgeccba")?
public static boolean isPal(String s){
if(s.length() <= 1) return true;
else if(s.charAt(0)!= s.charAt(s.length() -1)) return false;
else return isPal(s.substring(1,s.length()-1));
}
a.5
b.6
c.7
d.8
e.9
h.10
i.None of the above
4. How many times is the moveDisk method in the following code invoked for moveDisk(5)
public void moveDisks(int n, char fromTower, char toTower, char auxTower){
if(n==1){
System.out.println("Move disk " + n + " from " + fromTower + " to " + toTower + " ");
}else{
moveDisks(n-1, fromTower, auxTower, toTower);
System.out.println("Move disk " + n + " from " + fromTower + " to " + toTower + " ");
moveDisks(n-1, auxTower, toTower, fromTower);
}
}
a.15
b.16
c.18
d.24
e.31
f.63
g.72
h.84
i.127
j.None of the above
Explanation / Answer
1.
Answer : c. 6
Explanation: factorial(6)
6
6*5
6*5*4
6*5*4*3
6*5*4*3*2
6*5*4*3*2*1
2.
Answer : d. 15
Explanation : fib(5)
[(5)]+[(4)]
[(4)+(3)] + [(3)+(2)]
[(3)+(2) + (2)+(1)] + [(2)+(1) + (1)+(0)]
[(2)+(1) + (1)+(0) + (1)+(0)] + [(1)+(0)]
//similarly like this the function called for 15 times
3.
Answer : i. None of the above
Explanation : isPal("abcdeghiktkihgeccba")
1. abcdeghiktkihgeccba
2. bcdeghiktkihgeccb
3. cdeghiktkihgecc
4. deghiktkihgec
//function called for 4 times
//returns false
4.
Answer : e. 31
Explanation : moveDisk(5)
Move disk 1 from 1 to 2
Move disk 2 from 1 to 3
Move disk 1 from 2 to 3
Move disk 3 from 1 to 2
Move disk 1 from 3 to 1
Move disk 2 from 3 to 2
Move disk 1 from 1 to 2
Move disk 4 from 1 to 3
Move disk 1 from 2 to 3
Move disk 2 from 2 to 1
Move disk 1 from 3 to 1
Move disk 3 from 2 to 3
Move disk 1 from 1 to 2
Move disk 2 from 1 to 3
Move disk 1 from 2 to 3
Move disk 5 from 1 to 2
Move disk 1 from 3 to 1
Move disk 2 from 3 to 2
Move disk 1 from 1 to 2
Move disk 3 from 3 to 1
Move disk 1 from 2 to 3
Move disk 2 from 2 to 1
Move disk 1 from 3 to 1
Move disk 4 from 3 to 2
Move disk 1 from 1 to 2
Move disk 2 from 1 to 3
Move disk 1 from 2 to 3
Move disk 3 from 1 to 2
Move disk 1 from 3 to 1
Move disk 2 from 3 to 2
Move disk 1 from 1 to 2