英文:
Fibonacci sequence using array without using recursion technique
问题
这是方法:
public static void fibonacci_array_calc(int[] array) {
System.out.println("Fibonacci Series of " + array.length + " numbers:");
if (array.length > 0) {
System.out.print("0 ");
if (array.length > 1) {
System.out.print("1 ");
int prev = 0;
int current = 1;
for (int i = 2; i < array.length; i++) {
int next = prev + current;
System.out.print(next + " ");
prev = current;
current = next;
}
}
}
}
输出是:
Fibonacci Series of 10 numbers:
0 1 1 2 3 5 8 13 21 34
这段代码对于生成斐波那契数列使用了一个更简洁的方法,避免了重复的操作。
英文:
I'm trying to generate a code that will display the Fibonacci sequence using an array I did generate a code that has the right solution but I think it's too long since the instructor told us it's gonna be a maximum of 5 lines of code
So here is the method :
public static void fibonacci_array_calc(int[] array) {
int result;
System.out.println("Fibonacci Series of " + array.length + " numbers: ");
if (array.length == 0 || array.length == 1) {
for(int i = 0;i < array.length; i++)
System.out.print(array[i] + " ");
} else {
for (int i = 0; i <= 1; i++) {
result = array[i] = i;
System.out.print(result + " ");
if (array[i] >= 1) {
for (int j = 2; j < array.length; i++, j++) {
result = (array[j] = (array[i] + array[i - 1]));
System.out.print(result + " ");
}
}
}
}
}
the output is
Fibonacci Series of 10 numbers:
0 1 1 2 3 5 8 13 21 34
it's not allowed to use the recursion technique is there any way to shorten this code?
答案1
得分: 1
你可以通过使用条件赋值给array[i]
来极大简化你的代码。这个赋值可以在不论输入数组长度的情况下使用:
public static void fibonacci_array_calc(int[] array) {
System.out.println("Fibonacci 数列(包含 " + array.length + " 个数字):");
for (int i = 0; i < array.length; i++) {
array[i] = i <= 1 ? i : array[i-2] + array[i-1];
System.out.print(array[i] + " ");
}
}
英文:
You can greatly simplify your code by using a conditional assignment to array[i]
. This assignment can then be used regardless of the length of the input array:
public static void fibonacci_array_calc(int[] array) {
System.out.println("Fibonacci Series of " + array.length + " numbers: ");
for (int i = 0; i < array.length; i++) {
array[i] = i <= 1 ? i : array[i-2] + array[i-1];
System.out.print(array[i] + " ");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论