Fibonacci sequence using array without using recursion technique

huangapple go评论109阅读模式
英文:

Fibonacci sequence using array without using recursion technique

问题

这是方法:

  1. public static void fibonacci_array_calc(int[] array) {
  2. System.out.println("Fibonacci Series of " + array.length + " numbers:");
  3. if (array.length > 0) {
  4. System.out.print("0 ");
  5. if (array.length > 1) {
  6. System.out.print("1 ");
  7. int prev = 0;
  8. int current = 1;
  9. for (int i = 2; i < array.length; i++) {
  10. int next = prev + current;
  11. System.out.print(next + " ");
  12. prev = current;
  13. current = next;
  14. }
  15. }
  16. }
  17. }

输出是:

  1. Fibonacci Series of 10 numbers:
  2. 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 :

  1. public static void fibonacci_array_calc(int[] array) {
  2. int result;
  3. System.out.println(&quot;Fibonacci Series of &quot; + array.length + &quot; numbers: &quot;);
  4. if (array.length == 0 || array.length == 1) {
  5. for(int i = 0;i &lt; array.length; i++)
  6. System.out.print(array[i] + &quot; &quot;);
  7. } else {
  8. for (int i = 0; i &lt;= 1; i++) {
  9. result = array[i] = i;
  10. System.out.print(result + &quot; &quot;);
  11. if (array[i] &gt;= 1) {
  12. for (int j = 2; j &lt; array.length; i++, j++) {
  13. result = (array[j] = (array[i] + array[i - 1]));
  14. System.out.print(result + &quot; &quot;);
  15. }
  16. }
  17. }
  18. }
  19. }

the output is

  1. Fibonacci Series of 10 numbers:
  2. 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]来极大简化你的代码。这个赋值可以在不论输入数组长度的情况下使用:

  1. public static void fibonacci_array_calc(int[] array) {
  2. System.out.println("Fibonacci 数列(包含 " + array.length + " 个数字):");
  3. for (int i = 0; i < array.length; i++) {
  4. array[i] = i <= 1 ? i : array[i-2] + array[i-1];
  5. System.out.print(array[i] + " ");
  6. }
  7. }
英文:

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:

  1. public static void fibonacci_array_calc(int[] array) {
  2. System.out.println(&quot;Fibonacci Series of &quot; + array.length + &quot; numbers: &quot;);
  3. for (int i = 0; i &lt; array.length; i++) {
  4. array[i] = i &lt;= 1 ? i : array[i-2] + array[i-1];
  5. System.out.print(array[i] + &quot; &quot;);
  6. }
  7. }

huangapple
  • 本文由 发表于 2020年10月22日 07:32:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64473133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定