본문 바로가기

Study/BaekJoon

[백준 자바JAVA] 10826번 - 피보나치 수 4

728x90

https://www.acmicpc.net/problem/10826

 


● 문제

보기에는 간단한 피보나치 수열 문제 같지만 "10,000 보다 작거나 같은 자연수" 라는 조건 때문에 조금 까다로워진 문제였다.

int형과 long형 둘 로는 해결이 안되고 BigInteger라는 자료형을 사용해 해결해야 하는 문제이다.

BitInteger은 무한대를 커버할 수 있는 자료형으로 평소 사용하는 자료형과는 달리 여러 메소드들이 존재한다.


● 코드

import java.math.BigInteger;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int n = Integer.parseInt(br.readLine());

        BigInteger[] dp = new BigInteger[10001];

        dp[0] = BigInteger.ZERO;
        dp[1] = BigInteger.ONE;

        for(int i = 2; i <= n; i++) {
            dp[i] = dp[i - 2].add(dp[i - 1]);
        }

        System.out.println(dp[n]);
    }

}

 

 

728x90