Senior
Write a method that returns the N-th element of the Fibonacci sequence.
sobes.tech AI
Answer from AI
java public class Fibonacci { // Method returns the Nth element of the Fibonacci sequence (0-based) public static long fibonacci(int n) { if (n < 0) { throw new IllegalArgumentException("Index cannot be negative"); } if (n == 0) return 0; if (n == 1) return 1;
long a = 0;
long b = 1;
long result = 0;
for (int i = 2; i <= n; i++) {
result = a + b;
a = b;
b = result;
}
return result;
}
public static void main(String[] args) {
int n = 10;
System.out.println("Fibonacci(" + n + ") = " + fibonacci(n));
}
}