Home  >  Article  >  Java  >  Use Java to implement the sum of the first n terms of the Fibonacci sequence

Use Java to implement the sum of the first n terms of the Fibonacci sequence

无忌哥哥
无忌哥哥Original
2018-07-23 11:20:294744browse

Known: The first few numbers of the Fibonacci sequence are 0,1,1,2,3,5….

Starting from item 3, each item is equal to the sum of the previous two items. Read in an integer n and program to find the first n items of this sequence.
Note: The sequence here starts from 0.

import java.util.Scanner;

/**
 * FaibonacciNumber.java
 * @author anyunpei 2018年7月22日下午3:54:11
 * 计算faibonacci数列之和
 */
public class FaibonacciNumber {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int[] a = new int[n];
		a[0] = 0;
		a[1] = 1;
		System.out.println(a[0] + "\n" + a[1]);
		for (int i = 2; i < n; i++) {
			a[i] = a[i - 1] + a[i - 2];
			if (a[i] < 0) {
				System.out.println("请缩小此数列的项数,数列之和已溢出" + "最好保证在(" + i + ")项之内");
				return;
			}
			System.out.println(a[i]);
		}
	}
}

The above is the detailed content of Use Java to implement the sum of the first n terms of the Fibonacci sequence. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn