2016-11-13 33 views
1

該程序發現Fibonacci數與另一組,通過與2Fibonacci數數組和數組的另一副本的元素是2(歐拉習題2)整除,換出null元素

問題整除斐波納契數CODE:我無法刪除第二個數組的元素,即那些包含零或null的元素。

例如,以下示例輸出具有不符合斐林納西標準的零。這是能被2整除(即歐拉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] + " "); 
     } 
    } 
} 

回答

0

這是更好因爲Fibonacci數字的未知數可以被2整除,所以聲明divSeries爲ArrayList來存儲最終結果。

因此,該代碼將是:

//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 + " "); 
+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++; 
    } 
} 
+0

謝謝!這也工作。 –

0

不要刪除它們,不理會他們:

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

謝謝!這也工作。 –

相關問題