| 1234567891011121314151617181920212223242526272829303132 |
- import java.util.Scanner;
- class Fibonacci {
- public static void main(String[] args) {
- Scanner skn = new Scanner(System.in);
- int n;
- long res;
- try {
- n = skn.nextInt();
- } catch (java.util.InputMismatchException e) {
- System.out.println("Invalid input!");
- skn.close();
- return;
- }
-
- if (n < 1) {
- System.out.println("Invalid input! n cannot be negative!");
- skn.close();
- return;
- }
- double sqrt5 = Math.sqrt(5);
- res = Math.round((1/sqrt5) * (Math.pow((1 + sqrt5) / 2, n) - (Math.pow((1 - sqrt5) / 2, n))));
- if (res > Integer.MAX_VALUE) {
- System.out.println("Overflow!");
- } else {
- System.out.println(n + ". Fibonacci number: " + res);
- }
- skn.close();
- }
- }
|