잡다한 코딩/Project Euler (Java)

(Java) Project Euler 025 - 1000-digit Fibonacci Number

Skyleester_devNurse 2024. 1. 3. 18:00
// The Fibonacci sequence is defined by the recurrence relation:

// F(n) = F(n-1) + F(n-2), where F1 = 1 and F2 = 1.

// Hence the first 12 terms will be:

// 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.

// The 12th term, F(12), is the first term to contain three digits.

//What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

 

import java.math.BigInteger;

public class ProjectEuler_025 {
    public static void main(String[] args) {
        // 초기 피보나치 수 설정
        BigInteger fibNum_1 = BigInteger.ONE;
        BigInteger fibNum_2 = BigInteger.ONE;
        BigInteger fib = BigInteger.ZERO;

        // 초기 두 개의 피보나치 수 출력
        System.out.println(fibNum_1);
        System.out.println(fibNum_2);

        // 피보나치 수열의 인덱스
        long fibIndex = 3;

        // 무한 루프
        while (true) {
            // 현재 피보나치 수 계산
            fib = fibNum_1.add(fibNum_2);

            // 이전 두 개의 피보나치 수 갱신
            fibNum_1 = fibNum_2;
            fibNum_2 = fib;

            // 현재 피보나치 수 출력
            System.out.println(fib);

            // 현재 피보나치 수의 자릿수 계산
            int digitCount = fib.toString().length();

            // 자릿수가 1000 이상인 경우 루프 종료
            if (digitCount >= 1000) {
                break;
            }

            // 피보나치 수열의 인덱스 증가
            fibIndex += 1;
        }

        // 결과 출력
        System.out.println(fibIndex);
    }
}