码迷,mamicode.com
首页 > 其他好文 > 详细

杭大 1005 Number Sequence

时间:2018-09-23 13:51:43      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:dash   his   code   循环   ons   fine   ali   content   ext   

Number Sequence

Problem Description
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).
 
Input
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.
 
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
 0 0 0
Sample Output
2
5
原理:MOD7之后肯定有个周期,把他找出来,这题就完成了。具体如下
提示:周期是从第三个数开始,要不然会有下面这种情况
Sample input
7 7 10
则f[i]=1  1   0   0  0   0   0这种序列。很显然,周期是从第三个数开始循环的
 
#include<stdio.h>
int f[10000+5]={1,1,1};
int main()
{
    int a,b,n;
    while(scanf("%d%d%d",&a,&b,&n),a||b||n)
    {
        int i;
        if(n==2||n==1)
        {
            printf("1\n");
            continue;
        }
        for(i=3;i<100;i++)//i<100表示,假定周期不会超过100左右,不过超了就改大一点呗
        {
            f[i]=(a*f[i-1]+b*f[i-2])%7;
            if((i!=4&&f[i]==f[4]&&f[i-1]==f[3])||i-4>=n)
               break;
        }
        int T=i-2-2;//由于从第三个开始,所以周期T就有这样的表达式 
        printf("%d\n",f[(n-3)%T+3]);//n-3=n-2-1;  n-2表示是周期的第n-2个数,再减一,是为了取模时数的范围在0 ——(T-1)
//加三,是因为从第个开始 }
return 0; }

 

 
 

 

杭大 1005 Number Sequence

标签:dash   his   code   循环   ons   fine   ali   content   ext   

原文地址:https://www.cnblogs.com/shenyuling/p/9692200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!