fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4. public static int fibonacci(int n) {
  5. if (n <= 0) {
  6. return 0;
  7. }
  8. if (n == 1) {
  9. return 1;
  10. }
  11.  
  12. int f0 = 0;
  13. int f1 = 1;
  14. int fibo = 0;
  15.  
  16. // The C++ code calculates n steps starting from the 0th term (f0=0, f1=1).
  17. // To correctly calculate the nth Fibonacci number F(n), we need n-1 steps
  18. // starting from F(1). The original code returns F(n) at the end of the loop,
  19. // but the logic is slightly off. The standard iterative approach is safer.
  20. // We'll use the safer standard iterative loop for F(n).
  21.  
  22. for (int i = 2; i <= n; i++) {
  23. fibo = f0 + f1;
  24. f0 = f1;
  25. f1 = fibo;
  26. }
  27.  
  28. return f1;
  29. }
  30.  
  31. public static void main(String[] args) {
  32. Scanner scanner = new Scanner(System.in);
  33.  
  34. int n = scanner.nextInt();
  35.  
  36. System.out.println(fibonacci(n));
  37.  
  38. scanner.close();
  39. }
  40. }
Success #stdin #stdout 0.15s 56564KB
stdin
11
stdout
89