백준
백준 10826 피보나치 수 4(Java)
Park DJ
2023. 1. 23. 02:04
https://www.acmicpc.net/problem/10826
10826번: 피보나치 수 4
피보나치 수는 0과 1로 시작한다. 0번째 피보나치 수는 0이고, 1번째 피보나치 수는 1이다. 그 다음 2번째 부터는 바로 앞 두 피보나치 수의 합이 된다. 이를 식으로 써보면 Fn = Fn-1 + Fn-2 (n ≥ 2)가
www.acmicpc.net
해석 및 팁
이 문제는 단순히 int 또는 long을 사용하면 범위를 초과하기 때문에 BigInteger을 사용해주어야 합니다. BigInteger 배열을 선언한 후에 기존의 피보나치수열처럼 출력해 주시면 됩니다.
Java 코드
import java.util.Scanner;
import java.math.BigInteger; //BigInteger import
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigInteger[] arr = new BigInteger[n+1];
arr[0] = new BigInteger("0");
arr[1] = new BigInteger("1");
for(int i = 2; i <= n; i++) arr[i] = arr[i-1].add(arr[i-2]);
System.out.println(arr[n]);
}
}