A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
1.超内存了,第一反应:不应该用递归做,应该用迭代做
#include<stdio.h>
#include<iostream>
typedef long long LL;
const int mod = 7;
int a, b;
LL fabo(LL n)
{
if (n == 1)return 1;
else if (n == 2)return 1;
else
return (a*fabo(n - 1) + b*fabo(n - 2))%mod;
}
int main()
{
LL n;
while (scanf("%d%d%lld", &a, &b, &n) && a&&b&&n)
{
LL ans = fabo(n);
printf("%lld\n", ans);
}
return 0;
}
2.用迭代做,内存不超时间超
#include<stdio.h>
#include<iostream>
typedef long long LL;
const int mod = 7;
int a, b;
int main()
{
LL n;
while (scanf("%d%d%lld", &a, &b, &n) && a&&b&&n)
{
LL i;
LL f1 = 1, f2 = 1,cur=0;
if (n <= 1)cur = 1;
for (int i = 3; i <= n; i++)
{
cur = (a*f2 + b*f1)%mod;
f1 = f2;
f2 = cur;
}
printf("%lld\n", cur);
}
return 0;
}
3.应该是有规律了,本来第一感觉也是有规律,但是我是用笔算的,应该打表啊打表啊。打表但是各个周期都不一样 怎么办——所以,周期怎么算?(这个表没打最开始的两个1,1 Q_Q)
关于1,1的问题:
%7的值必然在0~6间循环,又由于一旦出现f(n-1)=0的情况后,f(n)便由f(n-1)唯一决定,所以一旦这个时候f(n-1)=1,则f(n)=1,所以每一个数列都是一个以0为末尾的循环,下一次一旦碰到1 1这样的序列的时候,另个循环就开始了
关于周期的问题:
取模的题目结果一般都有规律.两个数相加后对7取模,就有7*7=49种情况,即,周期为:49
对于公式 f[n] = A * f[n-1] + B * f[n-2]; 后者只有7 * 7 = 49 种可能,为什么这么说,因为对于f[n-1] 或者 f[n-2] 的取值只有 0,1,2,3,4,5,6 ,A,B固定的->只有49种可能值了
看了题解以后emmm
#include<string.h>
#include<stdio.h>
#include<iostream>
using namespace std;
typedef long long LL;
const int mod = 7;
int a, b,f[51];
int main()
{
LL n;
while (scanf("%d%d%lld", &a, &b, &n) &&( a||b||n))
{
f[0] = f[1] = f[2] = 1;
int i=0;
for (i = 3; i <= 50; i++)
{
f[i] = (a*f[i - 1] + b*f[i - 2]) % mod;
if (f[i] == 1 && f[i - 1] == 1)
break;
}
int tmp = i - 2;
if (n%tmp == 0)
printf("%d\n", f[tmp]);
else printf("%d\n", f[n%tmp]);
}
return 0;
}
补充一下斐波那契数列的板子(总是忘记)
int Fibonacci(int n)
{
if(n<=1)return n;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}
int Fibonacci1(int n)
{
int f0 = 0;
int f1 = 1;
int cur=0;
if(n<=1)return 0;
for(int i=2; i<=n;i++){
cur = f0 + f1;
f0 = f1;
f1 = cur;
}
return cur;
}