Java程式查詢斐波那契數列中偶數之和直到數字N


在本文中,我們將瞭解如何找到斐波那契數列中偶數之和直到數字N。斐波那契數列是由其前兩個整數之和形成的一系列數字。偶數斐波那契數列是斐波那契數列中的所有偶數。

斐波那契數列透過將前兩個數字相加生成後續數字。斐波那契數列從兩個數字開始 - F0 和 F1。F0 和 F1 的初始值可以分別取 0、1 或 1、1。

Fn = Fn-1 + Fn-2

因此,斐波那契數列可能如下所示:

F8 = 0 1 1 2 3 5 8 13

或者,這樣:

F8 = 1 1 2 3 5 8 13 21

以下是斐波那契數列偶數之和的演示:

輸入

假設我們的輸入是:

Value of n is: 10

輸出

期望的輸出將是:

Even sum of Fibonacci series is 10945

演算法

Step1- Start
Step 2- Declare three integers my_input, i, sum
Step 3- Prompt the user to enter two integer value/ Hardcode the integer
Step 4- Read the values
Step 5- Use a for loop to iterate through the integers from 1 to N and assign the sum of
consequent two numbers as the current Fibonacci number.
Step 6- Display the result
Step 7- Stop

示例 1

在這裡,輸入是根據提示由使用者輸入的。您可以在我們的程式碼練習工具 執行按鈕中即時嘗試此示例。

import java.util.Scanner;
import java.io.*;
public class FabonacciSum {
   public static void main(String[] args){
      int my_input, i, sum;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.println("Enter the value of N: ");
      my_input = my_scanner.nextInt();
      int fabonacci[] = new int[2 * my_input + 1];
      fabonacci[0] = 0;
      fabonacci[1] = 1;
      sum = 0;
      for (i = 2; i <= 2 * my_input; i++) {
         fabonacci[i] = fabonacci[i - 1] + fabonacci[i - 2];
         if (i % 2 == 0)
            sum += fabonacci[i];
      }
      System.out.printf("Even sum of fibonacci series till number %d is %d" , my_input, sum);
   }
}

輸出

Required packages have been imported
A reader object has been defined
Enter the value of N:
10
Even sum of fibonacci series till number 10 is 10945

示例 2

在這裡,整數已預先定義,並在控制檯上訪問和顯示其值。

import java.util.Scanner;
import java.io.*;
public class FabonacciSum {
   public static void main(String[] args){
      int my_input, j, sum;
      my_input = 10;
      System.out.println("The value of N: ");
      int fabonacci[] = new int[2 * my_input + 1];
      fabonacci[0] = 0;
      fabonacci[1] = 1;
      sum = 0;
      for (j = 2; j <= 2 * my_input; j++) {
          fabonacci[j] = fabonacci[j - 1] + fabonacci[j - 2];
          if (j % 2 == 0)
            sum += fabonacci[j];
      }
      System.out.printf("The even sum of fibonacci series till number %d is %d" , my_input, sum);
   }
}

輸出

The value of N:
The even sum of fibonacci series till number 10 is 10945

更新於: 2022年2月21日

3K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告