-->

별의 공부 블로그 🧑🏻‍💻
728x90

입력을 받으면, 입력한 수까지 피보나치 수열을 나열하는 프로그램

for 문/while 문/do while 문으로 간단하게 구현함.

(+ 재귀 함수/ goto 문 이용하기)


시간 복잡도 : O(n)


Fibonacci Sequence with C++

Basic Information

F_n
=> 0 (if n == 1)
=> 1 (if n == 2)
=> F_(n-1) + F_(n-2) (if n > 2)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 ...

Implementation

  • Date : December 28, 2020
  • Author : starrykss
  • Language : C++
  • Implementation Ways
    • Way 01. Implementation with for Statement
    • Way 02. Implementation with while Statement
    • Way 03. Implementation with do-while Statement
    • Way 04. Implementation with Recursive Function
    • Way 05. Implementation with goto Statement
view raw 00_Fibonacci.md hosted with ❤ by GitHub
#include <iostream>
using namespace std;
#define myInt unsigned long long int
int main() {
myInt num, prevValue = 0, curValue = 1;
cin >> num;
for (int i = 0; i <= num; i++) {
if (i == 0) {
cout << "0" << " ";
}
else if (i == 1) {
cout << "1" << " ";
}
else {
int nextValue = prevValue + curValue;
prevValue = curValue;
curValue = nextValue;
cout << curValue << " ";
}
}
return 0;
}
#include <iostream>
using namespace std;
#define myInt unsigned long long int
int main() {
myInt num, prevValue = 0, curValue = 1;
int i = 0;
cin >> num;
while (i <= num) {
if (i == 0) {
cout << "0" << " ";
}
else if (i == 1) {
cout << "1" << " ";
}
else {
int nextValue = prevValue + curValue;
prevValue = curValue;
curValue = nextValue;
cout << curValue << " ";
}
i++;
}
return 0;
}
#include <iostream>
using namespace std;
#define myInt unsigned long long int
int main() {
myInt num, prevValue = 0, curValue = 1;
int i = 0;
cin >> num;
do {
if (i == 0) {
cout << "0" << " ";
}
else if (i == 1) {
cout << "1" << " ";
}
else {
int nextValue = prevValue + curValue;
prevValue = curValue;
curValue = nextValue;
cout << curValue << " ";
}
i++;
} while (i <= num);
return 0;
}
#include <iostream>
using namespace std;
#define myInt unsigned long long int
myInt Fib(myInt n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return Fib(n - 1) + Fib(n - 2);
}
int main() {
myInt num;
cin >> num;
for (int i = 0; i <= num; i++) {
cout << Fib(i) << " ";
}
return 0;
}
#include <iostream>
using namespace std;
#define myInt unsigned long long int
int main() {
myInt num, prevValue = 0, curValue = 1;
cin >> num;
for (int i = 0; i <= num; i++) {
if (i <= 1) {
cout << i << " ";
}
else {
add:
int nextValue = prevValue + curValue;
prevValue = curValue;
curValue = nextValue;
cout << curValue << " ";
if (--num - 1) {
goto add;
}
}
}
return 0;
}

20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765


728x90


📖 Contents 📖
Fibonacci Sequence with C++Basic InformationImplementation