algorithm
피보나치 수열
juuuuuuun
2024. 4. 29. 14:30
설명
1) 피보나키 수열을 출력한다. 피보나치 수열이란 앞의 2개의 수를 합하여 다음 숫자가 되는 수열이다.
2) 입력은 피보나치 수열의 총 항의 수 이다. 만약 7이 입력되면 1 1 2 3 5 8 13을 출력하면 된다.
입력
첫 줄에 총 항수 N(3<=N<=45)이 입력된다.
출력
첫 줄에 피보나치 수열을 출력합니다.
예시 입력 1
10
예시 출력 1
1 1 2 3 5 8 13 21 34 55
소스 코드 1
import java.util.Scanner;
public class Main {
public static int[] solution(int N) {
int[] ans = new int[N];
for (int i = 0; i < ans.length; i++) {
if (i == 0 || i == 1) {
ans[i] = 1;
} else {
ans[i] = ans[i - 1] + ans[i - 2];
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for (int n : solution(N)) {
System.out.print(n + " ");
}
}
}