Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

피보나치 수열을 표시하는 Java 프로그램

<시간/>

이 기사에서는 숫자 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

입력

입력이 -

라고 가정합니다.
The input : 15

출력

원하는 출력은 -

The fibonacci series till 15 terms:

알고리즘

Step 1 - START
Step 2 - Declare values namely
Step 3 - Read the required values from the user/ define the values
Step 4 - 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 5- Display the result
Step 6- Stop

예시 1

여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. 피보나치 수열을 표시하는 Java 프로그램 .

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      int my_input , term_1, term_2, term_3;
      term_1 = 0;
      term_2 = 1;
      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.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      System.out.println("The fibonacci series till " + my_input + " terms:");
      for (int i = 1; i <= my_input; ++i) {
         System.out.print(term_1 + " ");
         term_3 = term_1 + term_2;
         term_1 = term_2;
         term_2 = term_3;
      }
   }
}

출력

Required packages have been imported
A reader object has been defined
Enter the number : 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

public class Main {
   public static void main(String[] args) {
      int my_input , term_1, term_2, term_3;
      my_input = 15;
      term_1 = 0;
      term_2 = 1;
      System.out.println("The number are defined as " +my_input );
      System.out.println("The fibonacci series till " + my_input + " terms:");
      for (int i = 1; i <= my_input; ++i) {
         System.out.print(term_1 + " ");
         term_3 = term_1 + term_2;
         term_1 = term_2;
         term_2 = term_3;
      }
   }
}

출력

The number are defined as 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377