user3395013 - 4 months ago 21

Java Question

Hi I have a homework question that needs some clarifications,

1.

`public int f (int n) {`

if (n < 0)

return 2;

else

return f (n - 1) + f (n - 3);

}

what is the value when the recall is f(3)

I know that this loops

so

`f(3) = f(2)+2`

= f(1)+2+2

= f(0)+2+2+2

= 8

but I'm not sure if Java considers 0 less than 0.

Answer

0 is not less than 0. It is equal to 0. Use `<=`

for "less than or equal to".

```
f(3) = f(3-1) + f(3-3)
f(3) = f(2) + f(0)
f(2) = f(2-1) + f(2-3)
f(2) = f(1) + f(-1)
f(1) = f(1-1) + f(1-3)
f(1) = f(0) + f(-2)
f(0) = f(-1) + f(-2)
f(N<0) = 2
```

Work your way back up.

```
f(0) = 2+2
f(1) = 2+2 +2
f(2) = 2+2+2 +2
f(3) = 2+2+2+2 +2+2
```