Advertisement
dimipan80

Fibonacci Numbers

Aug 6th, 2014
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. /* Write a program that reads a number n and prints on the console the first n members
  2.  * of the Fibonacci sequence (at a single line, separated by spaces) :
  3.  * 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ….
  4.  * Note that you may need to learn how to use loops. */
  5.  
  6. import java.util.Scanner;
  7.  
  8. public class FibonacciNumbers {
  9.  
  10.     public static void main(String[] args) {
  11.         // TODO Auto-generated method stub
  12.         Scanner scan = new Scanner(System.in);
  13.         System.out.print("Enter a positive number for N: ");
  14.         int numN = scan.nextInt();
  15.         scan.close();
  16.  
  17.         if (numN >= 1) {
  18.             long fib1 = 0;
  19.             System.out.printf("The first %d members of the Fibonacci sequence are:\n", numN);
  20.             System.out.print(fib1);
  21.             if (numN > 1) {
  22.                 long fib2 = 1;
  23.                 System.out.print(" " + fib2);
  24.                 for (int i = 3; i <= numN; i++) {
  25.                     long fibN = fib2 + fib1;
  26.                     System.out.print(" " + fibN);
  27.                     fib1 = fib2;
  28.                     fib2 = fibN;
  29.                 }
  30.             }
  31.         } else {
  32.             System.out.println("Error! - Your Number is Out of Range!!!");
  33.         }
  34.     }
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement