write a function to calculate the fibonacchi numbers in java
- User
write a function to calculate the fibonacchi numbers in java
Assistant
Sure! Here's an example function in Java to calculate the Fibonacci numbers:
codepublic static int fibonacci(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } return fibonacci(n-1) + fibonacci(n-2); }This function uses a recursive approach to calculate the Fibonacci numbers. It starts by checking if the input
nis equal to 0 or 1, in which case the result is 0 or 1, respectively. Otherwise, it calculates the Fibonacci number forn-1andn-2recursively and adds them together to get the result.Here's an example of how you can use this function:
codeSystem.out.println(fibonacci(5)); // Output: 5 System.out.println(fibonacci(8)); // Output: 21 System.out.println(fibonacci(13)); // Output: 89
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.