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

Number Sequence

2016-01-23 10:19 316 查看


[找规律] 杭电 hdu 1005 Number Sequence

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

思路:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. 其中1 <= n <= 100,000,000

由于n值非常大,逐个计算到f(n)肯定会超时。由mod 7容易想到会有规律可寻。

自定义A、B 寻找规律。

A=1,B=2时:

f3=3,f4=5,f5=4,f6=0,f7=1,f8=1.........得到周期为6。 算到这会有人以为周期就是6,实际上周期是不一定的,继续计算就会发现。

A=1,B=3时:

f3=4,f4=0,f5=5,f6=5,f7=6,f8=0,f9=4,f10=4,f11=2,f12=0,f13=6,f14=6,f15=3,f16=0,f17=2,f18=2,f19=1,f20=0,f21=3,f22=3,f23=5,f24=0,f25=1,f26=1.......得到周期为24。

A=1,B=4时:

f3=5,f4=2,f5=1,f6=2,f7=6,f8=0,f9=3,f10=3,f11=1,f12=6,f13=3,f14=6,f15=4,f16=0,f17=2,f18=2,f19=3,f20=4,f21=2,f22=4,f23=5,f24=0,f25=6,f26=6,f27=2,f28=5,f29=6,f30=5,f31=1,f32=0,f33=4,f34=4,f35=6,f36=1,f37=4,f38=1,f39=3,f40=0,f41=5,f42=5,f43=4,f44=3,f45=5,f46=3,f47=2,f48=0,f49=1,f50=1.......得到周期为48。

A=1,B=5时:

f3=6,f4=4,f5=6,f6=5,f7=0,f8=4,f9=4,f10=3,f11=2,f12=3,f13=6,f14=0,f15=2,f16=2,f17=5,f18=1,f19=5,f20=3,f21=0,f22=1,f23=1.........得到周期为21。

A=1,B=6时:

...

A=1,B=7时:

...

最后求出这些周期的最小公倍数为1008。

#include<iostream>

using namespace std;

int main()

{

int a,b,n,i;

while(scanf("%d%d%d",&a,&b,&n)&&a&&b&&n)

{

int f[1009];

f[1]=1;

f[2]=1;

for(i=3;i<=1008;i++)

{

f[i]=(a*f[i-1]+b*f[i-2])%7;

}

printf("%d\n",f[(n-1)%1008+1]);

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: