## DEV Community

Wahid Abduhakimov

Posted on • Updated on

# Fibonacci sonlari | C++ boshlang'ich

### Fibonacci

• `n` - fibonacci soni `n-1` va `n-2` fibonacci sonlari yig'indisiga teng.
• dastlabki 2 ta fibonacci sonlar `0` va `1` ga teng.

Dastlabki 10 ta fibonacci sonlarni hisoblab chop etadigan dastur tuzing.

``````int a = 0, b = 1, c = a + b;
cout << a << " " << b << " " << c << " ";
``````
• yuqorida dastlabki 3 ta fibonacci sonlar hisoblab chop etilgan

Keyingi fibonacci sonni hisoblab topish uchun so'ngi ikkita fibonacci sonlar `b` va `c`ni qo'shish kerak.

Lekin bu usul optimal kod emas, chunki yuqoridagi algoritm `reusable` emas. Ya'ni yuqoridagi algoritmni qaytarish orqali keyingi fibonaccini topib bo'lmaydi.

Quyidagi kodga qarang:

``````b = c;
a = b;
c = a + b;
cout << c << " ";
``````

Yuqoridagi kod optimal algoritm. Keyingi fibonaccini topish uchun yuqoridagi kodni shunchaki copy/paste qilish kifoya.

#### Barcha kod

``````int a = 0, b = 1, c = a + b;
cout << a << " " << b << " " << c << " "; // dastlabki 3 ta fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 4-fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 5-fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 6-fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 7-fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 8-fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 9-fibonacci

b = c;
a = b;
c = a + b;
cout << c << " ";   // 10-fibonacci
``````