Fibonacci数字阵列&另一个Array副本,其元素可以被2整除(Euler Prob 2),交换掉null元素

时间:2016-11-13 02:03:28

标签: java arrays null swap

该程序找到Fibonacci数和另一组可被2整除的Fibonacci数。

代码问题:我无法删除第二个数组的元素,即那些包含零或null的元素。

例如,以下示例输出具有不符合Fibinacci nos的零。可以被2整除(即,在Euler 2问题的调用下):

        Fib nos div by 2 except 0s: 
        0 2 0 0 8 0 0 34 0 0 144 0 0 610 0 0 2584 0 0 0

        The output should be:
        2 8 34 144 610 2584 

代码:

import java.util.Scanner; 

public class Fibonacci_Arrays {

    public static void main(String[] args) {
            int limit = 0;
            Scanner scan = new Scanner(System.in);
            //number of elements to generate in a series
            System.out.println("Enter how many Fibonacci numbers to generate: " + "\n");

            limit = scan.nextInt(); 

            long[] series = new long[limit]; //contains all of the Fib nos. to limit specified. 

            //create first 2 series elements
            series[0] = 0;
            series[1] = 1;

            long[] divSeries = new long[series.length]; //contains Fib nos. divisible by 2.

            //create the Fibonacci series and store it in an array
            for(int i=2; i < limit; i++){

                    series[i] = series[i-1] + series[i-2];
                    if ((series[i] % 2) == 0){
                        divSeries[i] = series[i];
                        //need to remove zero entries from the divSeries array.
                    }

            }

            //print the Fibonacci series numbers
            System.out.println("Fibonacci Series upto " + limit);
            for(int i=0; i< limit; i++){
                    System.out.print(series[i] + " ");
            }

            System.out.println(); 

            //print the Euler Problem 2 series numbers
            System.out.println("Fib nos div by 2 except 0s: ");
            for(int i=0; i< limit; i++){    
                System.out.print(divSeries[i] + " ");
        }
    }
}

3 个答案:

答案 0 :(得分:1)

为divseries使用不同的迭代器

int j = 0; //for divseries    
for(int i=2; i < limit; i++){

   series[i] = series[i-1] + series[i-2];

   if ((series[i] % 2) == 0){
       divSeries[j] = series[i];
       j++;
   }
}

答案 1 :(得分:0)

最好将divSeries声明为ArrayList来存储最终结果,因为Fibonacci数的未知数可被2整除。

所以,代码将是:

 //Contain the Fibonacci number divisible by 2.

 List<Long> divSeries = new ArrayList<>();

 for(int i=2; i < limit; i++){
      series[i] = series[i-1] + series[i-2];
      if ((series[i] % 2) == 0){ 
              divSeries.add(series[i]);
        }   
   }   

  //To print the result
  for(long i : divSeries)
        System.out.print(i + " ");

答案 2 :(得分:0)

不要删除它们,只需忽略它们:

for (long i : divSeries)
    if (i > 0) 
        System.out.print(i + " ");