HDOJ 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

 

此题是一个周期性循环的题目,很有技巧性

以下为分析:

既然A,B的值是一定的,而且前两个是1,1。那么后面的数就是固定的了,两两得一,必定还会出现1,1这种搭配,而当第一个1,1搭配出现的时候,也就是第一个最小周期出现的时候,也就是说,周期也就确定了。所以说后面的N不管有多大,只要除以周期,就转化成第一个最小周期中的某个数了。但是多大的范围下必定会再出现1,1搭配呢?首先,出现f(n)=1的概率为1/7,下一个仍然是f(n)=1的概率是1/7,所以1,1搭配出现的概率就是1/49。所以按照概率来讲,每49个数是必定会出现1,1搭配的。那么就从f(1)求到f(49)就够用了。也就是从这49个数中查找到真正的最小周期,代码如下:

#include<stdio.h>
int s[60];
int main()
{
 int A,B,n;
 while(scanf("%d%d%d",&A,&B,&n)!=EOF&&A&&B&&n)
 {
  int i,t;
  s[1]=1;
  s[2]=1;
  for(i=3;i<50;i++)//49之内必出规律
  {
   s[i]=(A*s[i-1]+B*s[i-2])%7;
   if(s[i]==1&&s[i-1]==1)
    break;
  }
  t=i-2;//得出最小周期数
  n=n%t;//得出最小周期数中与N结果等同的数
  if(n==0)
   n=t;
  printf("%d\n",s[n]);

 }
 return 0;
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值