Java Program to Generate Fibonacci Series in Reverse Order
Java Program to Generate Fibonacci Series in Reverse Order
The Fibonacci series is defined as follows:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
This can be represented as an array where: a[0] = 1, a[1] = 1, a[2] = 2, …, a[n] = a[n-1] + a[n-2].
This program, named 'TestFibonacci.java', reads two non-negative numbers (n and d) from the console using System.in. The program then outputs d elements of the series, starting from the n-th element, in reverse order to the console using System.out. You can assume that the input numbers are no larger than 100,000.
import java.util.*;
public class TestFibonacci {
static Scanner input = new Scanner(System.in);
// here is the function you need to implement
public static void parse_line(int n, int d) {
int[] f = new int[n + d];
f[0] = 1;
f[1] = 1;
for (int i = 2; i < n + d; i++) {
f[i] = f[i - 1] + f[i - 2];
}
int count = 0; // 计数器变量
for (int i = n - 1; i >= n - d; i--) {
System.out.print(f[i]);
count++;
if (count < d) {
System.out.print(", "); // 在最后一个元素之后停止添加逗号
}
}
}
public static void main(String[] args) throws Exception {
int line_number = Integer.parseInt(input.nextLine());
for (int i = 0; i < line_number; i++) {
String s = input.nextLine();
String t[] = s.split(", ");
int n = Integer.parseInt(t[0]);
int d = Integer.parseInt(t[1]);
TestFibonacci.parse_line(n, d);
System.out.println();
}
}
}
Explanation:
- Input: The program first reads the number of input lines (
line_number) followed byline_numberlines containing two integers separated by a comma and space (,). These integers representnanddrespectively. - Fibonacci Calculation: The
parse_linefunction calculates the Fibonacci series up ton + delements. This is done by iterating fromi = 2ton + d, adding the previous two elements (f[i-1]andf[i-2]) to get the current element (f[i]). - Reverse Order Output: The program then iterates from the
n-1th element to then-dth element. For each element, the program prints its value and increments a counter variable (count). If the counter is less thand, the program prints a comma and space (,) to separate the elements. This ensures that there is no comma after the last element.
Example Usage:
Input:
2
5, 3
10, 2
Output:
8, 5, 3
55, 34
This program demonstrates a simple yet efficient way to generate and manipulate Fibonacci sequences in Java. You can easily modify this code to adapt it to various scenarios involving Fibonacci sequences.
原文地址: https://www.cveoy.top/t/topic/bDMV 著作权归作者所有。请勿转载和采集!