[Solved] How to write Fibonacci in one line? [closed]


I expect you are looking for the ternary operator, which lets you compress conditional statements down into a single expression like so:

// returns the nth number in the fibonacci sequence
public static int fib(int n) { 
    return (n < 2) ? n : fib(n-1) + fib(n-2);
}

P.S.

This should work for both standard seed conditions of

F1 = 1
F2 = 1

or

F0 = 0
F1 = 1

See the Wikipedia article for a complete discussion of the math.

5

solved How to write Fibonacci in one line? [closed]