피버나치 수열은 다음과 같습니다...
오라클자바커뮤니티에서 설립한 오엔제이프로그래밍
실무교육센터
처음두수는 1이면서 다음과 같은 수열입니다...
1, 1, 2, 3, 5, 8, ,,,
f(n) = f(n-1) + f(n-2)
f(1) = 1, f(2) = 1
이를 자바에서 Queue를 이용하여 구현해 보았습니다...
- Queue에는 처음에 Fib[0] 과 Fib[1]이 들어가 있다.
- 다음의 Fib[2]를 계산할때 Fib[0]을 Queue 에서 제거한다.
-그 다음 계산된 Fib[2]를 다시 Queue에 삽입한다.
- 위의 과정을 반복한다.
아래예제를 참조하세요~
class FiboWithQueue {
void fibo(int n) {
int[] fib = new int[n];
int a, b;
ArrayQueue queue = new ArrayQueue(2);
fib[0] = fib[1] = 1;
queue.put(new Integer(1)); // fib(0)
queue.put(new Integer(1)); //fib(1)
for(int i=2; i<n; i++) {
a = ((Integer)queue.getFrontElement()).intValue();
b = ((Integer)queue.getRearElement()).intValue();
fib[i] = a + b;
queue.remove();
queue.put(new Integer(fib[i]));
}
//------------ 수열 출력
for(int i=0; i<fib.length; i++) {
System.out.println(fib[i] + " ");
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage : java FiboWithQueue number");
System.exit(1);
}
int n = Integer.parseInt(args[0]);
FiboWithQueue f = new FiboWithQueue();
f.fibo(n);
}
}
(신입사원채용무료교육, 오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷)
처음두수는 1이면서 다음과 같은 수열입니다...
1, 1, 2, 3, 5, 8, ,,,
f(n) = f(n-1) + f(n-2)
f(1) = 1, f(2) = 1
이를 자바에서 Queue를 이용하여 구현해 보았습니다...
- Queue에는 처음에 Fib[0] 과 Fib[1]이 들어가 있다.
- 다음의 Fib[2]를 계산할때 Fib[0]을 Queue 에서 제거한다.
-그 다음 계산된 Fib[2]를 다시 Queue에 삽입한다.
- 위의 과정을 반복한다.
아래예제를 참조하세요~
class FiboWithQueue {
void fibo(int n) {
int[] fib = new int[n];
int a, b;
ArrayQueue queue = new ArrayQueue(2);
fib[0] = fib[1] = 1;
queue.put(new Integer(1)); // fib(0)
queue.put(new Integer(1)); //fib(1)
for(int i=2; i<n; i++) {
a = ((Integer)queue.getFrontElement()).intValue();
b = ((Integer)queue.getRearElement()).intValue();
fib[i] = a + b;
queue.remove();
queue.put(new Integer(fib[i]));
}
//------------ 수열 출력
for(int i=0; i<fib.length; i++) {
System.out.println(fib[i] + " ");
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage : java FiboWithQueue number");
System.exit(1);
}
int n = Integer.parseInt(args[0]);
FiboWithQueue f = new FiboWithQueue();
f.fibo(n);
}
}
댓글 없음:
댓글 쓰기