The fibonacci sequence is a sequence of numbers in which the next number is the sum of the previous two numbers.
The first two numbers of the fibonacci sequence are 0, 1.
The first 8 numbers of the fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13
Write some code to print out the first X numbers of the fibonacci sequence.
Your output should be on one line, with each number separated by a space. You may assume that x is at least 2.
Solution
Recursion basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class Bakjoon {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
int x = inp.nextInt();
//write your code below
for(int i=0;i<x;i++) {
System.out.print(Fibonacci(i)+" ");
}
}
public static int Fibonacci(int n) {
if(n==0){
return 0;
}
else if(n <= 2)
return 1;
else
return Fibonacci(n-1) + Fibonacci(n-2);
}
}
|
반응형
'Java_beginner(Repl.it) > Auto-Graded-Course(AP CS A)' 카테고리의 다른 글
034 - Big Number Program (From Decoding) (0) | 2019.12.10 |
---|---|
033 - For Loop Challenge 2 (optional) (0) | 2019.12.07 |
031 - Further For Loop Practice 7 (mIxEd CaSe) (0) | 2019.12.07 |
030 - Further For Loop Practice 6 (reverse string) (0) | 2019.12.07 |
029 - Further For Loop Practice 5 (printing characters) (0) | 2019.12.07 |