转载出处点击打开链接
//『参考网上牛人的』
#include <stdio.h>
# include <iostream>
using namespace std;
int main(void)
{
int a=0,b=0,n=0;
int i=0;
int circlestart=0;
int remainder[50]={1,1};
while(cin>>a>>b>>n && (a||b||n))
{
i=1;
circlestart=0;
a%=7;
b%=7;
while (++i<n)
{
remainder[i]=(a*remainder[i-1]+b*remainder[i-2])%7;
if ((remainder[i]==1 && remainder[i-1]==1)
|| (i>3 && remainder[i]==remainder[3] && remainder[i-1]==remainder[2] && (circlestart=2)))
break;
}
if (i==n)//至 i==n 处仍未有循环
printf("%d\n",remainder[i-1]);
else if ((n-circlestart)%(i-circlestart-1)==0)//n处正好为整数个循环
printf("%d\n",remainder[i-2]);
else
printf("%d\n",remainder[(n-circlestart)%(i-circlestart-1)+circlestart-1]);
}
return 0;
}
不过上述程序是事先已经知道那些ab的特殊组合是从第二个元素开始循环的,一种更普遍的方法如下:
#include <iostream>
#include <vector>
using namespace std;
vector<int> ivec;
//布尔数组元素flag[i][j]如果为true,则说明前面已经出现了i 和 j两者的组合
bool flag[7][7];
void init(void)
{
int i,j;
for(i = 0;i < 7;++i)
for(j = 0;j< 7;++j)
flag[i][j] = false;
}
int main()
{
int a,b,n;
while(cin>>a>>b>>n)
{
if(a == 0&&b == 0&&n == 0)
break;
ivec.clear();
init();
ivec.push_back(1);
ivec.push_back(1);
flag[1][1] = true;
int count = 1,f;
while(1)
{
f = (a*ivec.at(count)%7 + b*ivec.at(count - 1)%7)%7;
ivec.push_back(f);
++count;
//如果flag变量为true,则说明前面已经出现了这两者的组合,出现重复,无需下一步计算,直接break退出即可
if(flag[ivec.at(count)][ivec.at(count - 1)] == true)
break;
else
flag[ivec.at(count)][ivec.at(count - 1)] = true;
}
//count中存放的是ivec中出现循环前的元素总个数,注意ivec中的下标是从0开始计数的
count = count - 1;
if(n < count)
cout<<ivec.at(n-1)<<endl;
else
{
int j;
//for循环的目的是找出从那个地方开始重复,此处应该是从j处开始循环,注意j是从0下标开始计数的
for(j = 0;;++j)
if(ivec.at(count) == ivec.at(j) && ivec.at(count + 1) == ivec.at(j+1))
break;
n = (n - j)%(count - j);
if(n == 0)
n = count - j;
n += j;
cout<<ivec.at(n-1)<<endl;
}
}
return 0;
}
另外一个他人代码:
解题思路:
1.n的数值很大,这类数值很大的问题一般都有规律,找出循环节(周期)是关键;
2.找规律,这道题是从 f(1) = 1 和 f(2) = 1 开始,然后依次模7,可知 f(n) 只有7种情况,所以两数相邻只有7*7=49种;
3.所以从 f(1) 到 f(49) 必会出现相邻两个 f(m-1) = 1 , f(m) = 1,所以 f(n) 为周期函数,49为其一个周期;
需要注意的地方:
做题的时候不要盲目的上手去做,先要仔细分析题目,先动脑再动手。
代码如下:
// hdoj_1005 Number Sequence
// 31MS 220K 370 B GCC
#include <stdio.h>
int fun(int a, int b, __int64 n);
int main(void)
{
int a, b;
__int64 n;
while(scanf("%d%d%I64d", &a, &b, &n) && a != 0 && b != 0 && n != 0)
{
printf("%d\n", fun(a, b, n%49));
}
return 0;
}
int fun(int a, int b, __int64 n)
{
if(n == 1 || n == 2)
return 1;
else
return (a*fun(a, b, n-1) + b*fun(a, b, n-2)) % 7;
}