C语言斐波那契数列除以10007余数
时间: 2023-11-25 10:51:23 浏览: 51
以下是C语言实现斐波那契数列除以10007余数的代码:
```c
#include <stdio.h>
int main() {
int i = 1, j = 1, n;
scanf("%d", &n);
if (n == 1 || n == 2) {
printf("1");
return 0;
}
int sum = 0;
for (int t = 3; t <= n; ++t) {
sum = (i + j) % 10007;
i = j % 10007;
j = sum % 10007;
}
printf("%d", sum);
return 0;
}
```
这段代码通过循环计算斐波那契数列的每一项,并在计算过程中对10007取余,最终得到斐波那契数列除以10007的余数。
相关问题
斐波那契数列除以10007余数
斐波那契数列是指:第一项和第二项均为1,从第三项开始,每一项都是前两项的和。斐波那契数列除以10007的余数可以通过以下代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
int i = 1, j = 1, n;
cin >> n;
if (n == 1 || n == 2) {
cout << "1";
return 0;
}
int sum = 0;
for (int t = 3; t <= n; ++t) {
sum = (i + j) % 10007;
i = j % 10007;
j = sum % 10007;
}
cout << sum;
return 0;
}
```
以上代码中,我们使用了循环来计算斐波那契数列的第n项除以10007的余数。在循环中,我们使用了三个变量i、j和sum,分别表示斐波那契数列的第n-2项、第n-1项和第n项。在每次循环中,我们将i和j的余数相加,再对10007取余,得到斐波那契数列的第n项除以10007的余数。最后输出sum即可。
斐波那契数列递归除以10007
根据提供的引用内容,斐波那契数列的递推公式为:Fn=Fn-1+Fn-2,其中F1=F2=1。当n比较大时,Fn也非常大,现在我们想知道,Fn除以10007的余数是多少。为了避免使用递归算法,我们可以使用循环来实现。以下是C++代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
int i = 1, j = 1, n;
cin >> n;
if (n == 1 || n == 2) {
cout << "1";
return 0;
}
int sum = 0;
for (int t = 3; t <= n; ++t) {
sum = (i + j) % 10007;
i = j % 10007;
j = sum % 10007;
}
cout << sum;
return 0;
}
```
在上述代码中,我们使用了循环来计算斐波那契数列的值,并在每次计算后对10007取余,以避免计算结果过大。如果n等于1或2,则直接输出1。否则,我们使用循环计算斐波那契数列的值,并在每次计算后对10007取余,最终输出结果。