ในบทความนี้ เราจะเข้าใจวิธีการหาผลรวมคู่ของอนุกรมฟีโบนักชีจนถึงหมายเลข 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