Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
What is the output of this function?
int Fun(int n)
{
If (n==0)
return 2;
else
return 4 + fun(n/2);
}
4 Answers
- brilliant_movesLv 78 years agoFavorite Answer
Run the following Java code for your answer:
public class OutputOfFunction {
public static void main(String[] args) {
for (int i=0; i<25; i++) {
System.out.println("fun("+i+") = "+fun(i));
}
}
static int fun(int n) {
if (n==0)
return 2;
else
return 4 + fun(n/2);
}// end fun
} // end class
Source(s): Experience - ?Lv 68 years ago
For the code above (except it should be Fun(n/2)) ... for n=0 to 24 ... results below ... looks like at the change of any "2 to the power of" we increase by 4 after starting with 2 at the start ... so at 2 to the power of 0 (=1) we get 2+4=6, at 2 to the power of 1 (=2) we get 6+4=10, at 2 to the power of 2 (=4) we get 10+4=14, at 2 to the power of 3 (=8) we get 14+4=18 etcetera ... values between show no change:
[Session started at 2012-12-13 20:29:11 +1100.]
Fun(0) is 2
Fun(1) is 6
Fun(2) is 10
Fun(3) is 10
Fun(4) is 14
Fun(5) is 14
Fun(6) is 14
Fun(7) is 14
Fun(8) is 18
Fun(9) is 18
Fun(10) is 18
Fun(11) is 18
Fun(12) is 18
Fun(13) is 18
Fun(14) is 18
Fun(15) is 18
Fun(16) is 22
Fun(17) is 22
Fun(18) is 22
Fun(19) is 22
Fun(20) is 22
Fun(21) is 22
Fun(22) is 22
Fun(23) is 22
Fun(24) is 22
Source(s): XCode C++ (or Java) on a Mac - OneLv 68 years ago
answer will be 2 if n= o else 4+ fun(n/2). This is called recursion . Let say n = 8
then answer will be: 8/2= 4/2= 2/2= 1/2 =0 = 4 +4 +4+4+4 =20.
i.e. 4 + (number of times you can divide number by 2)* 4
so for n = 13
13/2 =6/2 =3/2= 1/2= 0 = 4*4 + 4= 20
- 8 years ago
fun(4);
/
fun(3), print(3), fun(2)(prints 0 1)
/
fun(2), print(2), fun(1)(prints 0)
/
fun(1), print(1), fun(0)(does nothing)
/
fun(0), print(0), fun(-1) (does nothing)
Source(s): http://www.ksdesigners.com/