HDU_1005

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 198973    Accepted Submission(s): 49928


 

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 Output2

5

分析

这一题是大数递归求值,用简单的递归算法会是超时。观察到函数中对7取余的结果是0-6.

而对于此函数,数列前两个数相同,后面的数都相同。对于0-6组成的数列,每49个数就会出现相同的连续两数。所以输出组成的是一个循环数列,现在关键是求出循环周期T。通过查询找出第二次出现的 1 1 数列,位置减得周期T。

#include<stdio.h>
int main()
{
	int a,b,n,i;
	while(scanf("%d%d%d",&a,&b,&n),a||b||n)
	{
		int result[50]={1,1};
		for(i=2;i<50;i++)
		{
			result[i]=(result[i-1]*a+result[i-2]*b)%7;
			if(result[i]==1&&result[i-1]==1)
				break;
		}
		int t=i-1;
		if(n%t)
			printf("%d\n",result[n%t-1]);
		else
			printf("%d\n",result[t-1]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_18722465/article/details/81111585