您的位置:首页 > 产品设计 > UI/UE

递推和递归Number Sequence

2014-01-18 20:57 113 查看

Number Sequence

Time Limit: 1000MS Memory limit: 65536K

题目描述

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).

输入

The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.

输出

For each test case, print the value of f(n) on a single line.

示例输入

1 1 3
1 2 10
0 0 0


示例输出

2
5


提示

知识扩展:本类算法在数字医疗、移动证券、手机彩票、益智类解谜类游戏软件中会经常采用。

#include <stdio.h>
int k[1000]={0, 1, 1};
int main()
{
int i,a,b;
int n;
while(~scanf("%d %d %d",&a,&b,&n))
{
if(a==0&&b==0&&n==0)
break;
if(n>=3)
{

for(i=3;i<=1000;i++)
{
k[i]=(a*k[i-1]+b*k[i-2])%7;
if(k[i]==1&&k[i-1]==1)
break;
}
i-=2;//找循环节的最后一个数
n=n%i;//使n变成与第一个循环节中相等的数,也就是说把n变小
if(n==0)//表示是循环节最后一个数
printf("%d\n",k[i]);
else
printf("%d\n",k
);

}
else
printf("1\n");
}
return 0;
}


思考:1. 关于此题许多同胞都会感到头疼,所以说一下。。

第一次做我超时了, 原因是我把for(i=3;i<=100000000;i++) ,i的循环结束为i=100000000,先打表,然后再输出,这种算法此时肯定超时了, 所以呢。。 换了一种算法——如上代码。 可以讨论讨论啦~~~
2. 其实当a, b确定时,可以把循环节求出来,这里只须打印一下 i 即可,可确定循环节为48哦, 所以i<=50即可。。节省空间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: