Fibonacci.java 767 B

1234567891011121314151617181920212223242526272829303132
  1. import java.util.Scanner;
  2. class Fibonacci {
  3. public static void main(String[] args) {
  4. Scanner skn = new Scanner(System.in);
  5. int n;
  6. long res;
  7. try {
  8. n = skn.nextInt();
  9. } catch (java.util.InputMismatchException e) {
  10. System.out.println("Invalid input!");
  11. skn.close();
  12. return;
  13. }
  14. if (n < 1) {
  15. System.out.println("Invalid input! n cannot be negative!");
  16. skn.close();
  17. return;
  18. }
  19. double sqrt5 = Math.sqrt(5);
  20. res = Math.round((1/sqrt5) * (Math.pow((1 + sqrt5) / 2, n) - (Math.pow((1 - sqrt5) / 2, n))));
  21. if (res > Integer.MAX_VALUE) {
  22. System.out.println("Overflow!");
  23. } else {
  24. System.out.println(n + ". Fibonacci number: " + res);
  25. }
  26. skn.close();
  27. }
  28. }