Calculates the Fibonacci Sequence to the nth position. - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Calculates the Fibonacci Sequence to the nth position.

Demo Code

/*//from  ww w . ja va  2s .c om
 * Copyright (c) 2011-Present. Codeprimate, LLC and authors.  All Rights Reserved.
 * 
 * This software is licensed under the Codeprimate End User License Agreement (EULA).
 * This software is proprietary and confidential in addition to an intellectual asset
 * of the aforementioned authors.
 * 
 * By using the software, the end-user implicitly consents to and agrees to be in compliance
 * with all terms and conditions of the EULA.  Failure to comply with the EULA will result in
 * the maximum penalties permissible by law.
 * 
 * In short, this software may not be reverse engineered, reproduced, copied, modified
 * or distributed without prior authorization of the aforementioned authors, permissible
 * and expressed only in writing.  The authors grant the end-user non-exclusive, non-negotiable
 * and non-transferable use of the software "as is" without expressed or implied WARRANTIES,
 * EXTENSIONS or CONDITIONS of any kind.
 * 
 * For further information on the software license, the end user is encouraged to read
 * the EULA @ ...
 */

public class Main{
    /**
     * Calculates the Fibonacci Sequence to the nth position.
     *
     * @param n an integer value indicating the position of the nth element in the Fibonacci Sequence.
     * @return an integer array containing n elements of the Fibonacci Sequence.
     * @throws IllegalArgumentException if the position (n) is less than 1.
     */
    public static int[] fibonacciSequence(final int n) {
        Assert.argument(
                n > 0,
                "The number of elements from the Fibonacci Sequence to calculate must be greater than equal to 0!");

        int[] fibonacciNumbers = new int[n];

        for (int position = 0; position < n; position++) {
            if (position == 0) {
                fibonacciNumbers[position] = 0;
            } else if (position < 2) {
                fibonacciNumbers[position] = 1;
            } else {
                fibonacciNumbers[position] = (fibonacciNumbers[position - 1] + fibonacciNumbers[position - 2]);
            }
        }

        return fibonacciNumbers;
    }
}

Related Tutorials