Title description
Xiao Suan Suan recently learned the Fibonacci sequence.
The Fibonacci sequence refers to a sequence of numbers: the first and second numbers of the sequence are both 1, and each subsequent number is equal to the sum of the previous two numbers.
Given a positive integer k, what is the kth number in the Fibonacci sequence.
Input format
Input one line, including a positive integer k. (1 ≤ k ≤ 46)
Output format
Output one line, containing a positive integer, which represents the kth number in the Fibonacci sequence.
Sample Input
19
Sample Output
4181
Ideas
The key to this question is to find the recurrence formula. The first and second terms of the Fibonacci sequence are both 1. Starting from the third term, each term is equal to the sum of the previous two items, so the recurrence formula is obtained: a[i] = a[i-1] + a[i-2].
C language code:
#include<stdio.h>
int a[55];
int main()
{
a[0] = 0;
a[1] = 1;
a[2] = 1;
int k;
scanf("%d", &k);
for (int i = 3; i <= 50; i++)
a[i] = a[i - 1] + a[i - 2];//递推公式
printf("%d", a[k]);
return 0;
}
C++ code:
#include<bits/stdc++.h>
using namespace std;
long long num[50] = {
0};
void Init()
{
num[1] = 1;
num[2] = 1;
num[3] = 2;
for(int i = 4; i < 50; i++)
num[i] = num[i - 1] + num[i - 2];
}
int main()
{
int n;
Init();
while(cin >> n)
cout << num[n] << endl;
return 0;
}