Number Sequence (HDoj1005)

时间:2022-09-06 03:06:21
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
 
除了f1 和f2以外,每个数字都由前两个数字决定,这个是公式确定的也就是说,如果对于数列f1 f2 ..fa fb .fc fd 存在fa=fc且fd=fb 那么后续的一定循环,对于任意的fn,由于是mod 7所以其取值只能是0 1 2 3 4 5 6这7种可能这样对于任意的连续两个数字,fa fb,可能的组合就是7*7=49种,而实际上,0,0序列是一个特殊的情况,除非A B都是7的倍数,那么所有序列都是0,不然是不会出现00的可能的.所以,如果提取一个长为50的任意子序列,可以提取出49个连续对,这49个中肯定会有至少一个重复,也就是循环周期了.当时没做出来,看的题解,重点是找出循环节
 #include<stdio.h>
#include<math.h>
int f(int a,int b,int n)
{
if(n==)
return ;
if(n==)
return ;
return (a*f(a,b,n-)+b*f(a,b,n-))%;
}
int main()
{
int a,b;
int n;
while(scanf("%d%d%d",&a,&b,&n)==)
{
if(a==b&&b==n&&n==)
break;
else
printf("%d\n",f(a,b,n%));
}
}