Fibonacci Series

beginner Series and Sequences

Problem

Read n and print the first n terms of the Fibonacci series. The first two terms are 0 and 1. Every other term is the sum of the two terms before it: 0 1 1 2 3 5 8 ...

Constraints

  • 0 <= n <= 60

Examples

Input

6

Output

0 1 1 2 3 5

Solutions

Best approachTime O(n)Space O(n)

Each term is calculated from earlier terms and saved in an array.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Print the first n terms of the fibonacci series.
 * Input   : One integer n (number of terms).
 * Output  : The first n terms on one line, separated by a space.
 * Approach: Calculate each term from the earlier terms.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int count = new Scanner(System.in).nextInt();

        // Step 1: Make an array for the terms. Index 0 holds the first term.
        long[] terms = new long[count];

        // Step 2: Calculate the terms one by one.
        for (int index = 0; index < count; index++) {
            if (index < 2) {
                // Step 3: The first 2 terms are given. Term 0 is 0 and term 1 is 1.
                terms[index] = index;
            } else {
                // Step 4: Every other term comes from earlier terms. Add the two terms before it.
                terms[index] = terms[index - 1] + terms[index - 2];
            }
        }

        // Step 5: Print all terms on one line, separated by a space.
        StringBuilder line = new StringBuilder();
        for (int index = 0; index < count; index++) {
            if (index > 0) {
                line.append(" ");
            }
            line.append(terms[index]);
        }
        System.out.println(line);
    }
}
Hints (2)
  1. Which terms are given at the start?
  2. Which earlier terms do you need for the next term?