-3

i have the code:

public static void main(String[] args) {
        System.out.println(f(4));

    }

    public static int f(int n){
        if(n == 1) return 1;

        return n / f(n - 1);
    }

why this code return 4 ?

gigs
  • 1,241
  • 2
  • 15
  • 25

2 Answers2

1

f(1) will explicitly return 1

f(2) will give 2/f(1)==2/1==2

f(3) will give 3/f(2)==3/2==1 (int division)

f(4) will give 4/f(3)==4/1==4

khelwood
  • 55,782
  • 14
  • 81
  • 108
0
f(4) -> 4/f(3)
f(3) -> 3/f(2)
f(2) -> 2/f(2)
f(1) -> 1

Subtituting values

f(2) -> 2/1 => 2
f(3) -> 3/2 => 1 (since the return value is 1, 1.5 will be converted to 1)
f(4) -> 4/1 => 4
usha
  • 28,973
  • 5
  • 72
  • 93