본문 바로가기
Algorithm/백준

[백준] 피보나치 함수 1003번 - java

by jackWillow 2021. 11. 2.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
	private static int[][] zo = new int[41][2];
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int T = Integer.parseInt(br.readLine());
		zo[0][0] = 1;
		zo[0][1] = 0;
		zo[1][0] = 0;
		zo[1][1] = 1;
		
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < T; i++) {
			int n = Integer.parseInt(br.readLine());
			int[] ret = fibo(n);
			sb.append(ret[0]).append(' ').append(ret[1]).append('\n');
		}
		
		bw.write(sb.toString());
		
		bw.flush();
		bw.close();
		br.close();
	}
	
	private static int[] fibo(int n) {
		if(n <= 1) {
			return zo[n];
		}
		if(zo[n][0] != 0) {
			return zo[n];
		}
		
		int[] p1 = fibo(n - 1);
		int[] p2 = fibo(n - 2);
		zo[n][0] = p1[0] + p2[0];
		zo[n][1] = p1[1] + p2[1];
		return zo[n];
	}
}
반응형