斐波那契数的第n个数代码分享(c基础)
1:迭代
//斐波那契数的第n个数
#include<stdio.h>
//unsigned long long Fib(n)
//{
//
// if (1 == n || 2 == n)
// return 1;
// else return Fib((n - 1) + Fib((n - 2);
//
//
//}
unsigned long long Fib(n)
{
if (n == 1 || n == 2)
return 1;
else
{
int j = 3;
unsigned long long answer1 = 1;
unsigned long long answer2 = 1;
do
{
unsigned long long a = answer1;
answer1 = answer1 +answer2;
answer2 = a;
j++;
} while (j <= n);
return answer1;
}
}
int main()
{
int n = 0;
while(1)
{
scanf_s("%d", &n);
printf("%llu\n", Fib(n));
}
return 0;
}
2:递归
//斐波那契数的第n个数
#include<stdio.h>
unsigned long long Fib(n)
{
if (1 == n || 2 == n)
return 1;
else return Fib(n - 1) + Fib(n - 2);
}
//unsigned long long Fib(n)
//{
//
// if (n == 1 || n == 2)
// return 1;
// else
// {
// int j = 3;
// unsigned long long answer1 = 1;
// unsigned long long answer2 = 1;
//
// do
// {
// unsigned long long a = answer1;
// answer1 = answer1 +answer2;
// answer2 = a;
// j++;
// } while (j <= n);
// return answer1;
// }
//
//
//}
int main()
{
int n = 0;
while(1)
{
scanf_s("%d", &n);
printf("%llu\n", Fib(n));
}
return 0;
}