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+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.