Java examples for java.lang:Math Geometry Shape
Gets the Fibonacci number at position n in the Fibonacci Sequence.
/*//from www .ja va2s .c o m * 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{ /** * Gets the Fibonacci number at position n in the Fibonacci Sequence. * * @param n an integer value indicating the nth number in the Fibonacci Sequence. * @return the nth number in the Fibonacci Sequence. * @throws IllegalArgumentException if the position (n) is less than 1. * @see #fibonacciSequence(int) */ public static int fibonacciNumber(final int n) { return fibonacciSequence(n)[n - 1]; } /** * 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; } }