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
 首先想到了暴力:
#include<stdio.h>
int main(void)
{
int a, b, n;
int f1, f2, f3;
while()
{
scanf("%d%d%d", &a, &b, &n);
if(a== && b== && n==)
break;
f1 = ;
f2 = ;
f3 = ;
for(int i = ; i <= n; i++)
{
f3 = (a*f2 + b*f1)%;
f1 = f2;
f2 = f3;
}
printf("%d\n", f3);
} return ;
}

可惜暴力的后果是WA,再仔细看一下数据范围,n的取值达到一亿。由于数据范围很大,因此这题不适合暴力。

那么这道类似斐波那契数列的题目该如何搞呢?很明显,f(n-1)和f(n-2)的取值只可能有0, 1, 2, 3, 4, 5, 6这七种情况。因此f(n-1)+f(n-2)的组合一共有7*7种情况,这说明什么呢?说明数列(以f3作为第一个数)出现循环最多在第50个数(最坏的情况,可由鸽巢原理得出)。

修改后的程序:

#include<stdio.h>
int main(void)
{
int f1, f2, a, b, n, i;
int arr[]; // 空间够用的话多开点没坏处
while()
{
scanf("%d%d%d", &a, &b, &n);
if(a == && b == && n == )
break;
f1 = f2 = ;
for(i = ; ; i++) // 一定会结束,因为最多在第50个数出现循环,其中i-1是循环周期
{
arr[i] = (a*f2 + b*f1)%;
f1 = f2;
f2 = arr[i];
if(i >= && arr[i-] == arr[] && arr[i] == arr[] )
break;
}
if(n == || n == )
printf("1\n");
else
printf("%d\n", arr[(n-)%(i-)]);
} return ;
}

最新文章

  1. 关键字sizeof---常年被人误认为函数
  2. Atititcmd cli环境变量的调用设置与使用
  3. iOS 使用GCD实现倒计时效果
  4. Spark K-Means
  5. 【T-SQL系列】常用函数—聚合函数
  6. JSON 换行、JSON \r\n、怎么处理 ?(转载)
  7. postgresql 入门(含java、scala连接代码)
  8. IE11下用forms身份验证的问题
  9. Linux vsftpd 无法登录 cannot change directory:xxx priv_sock_get_cmd 问题
  10. C#错误异常列表
  11. boost
  12. Linux第八讲随笔 -tar / 系统启动流程
  13. ksar、sar及相关内核知识点解析
  14. React 面向组件化编程 - 封装了webpack - npm run build 产生的包的 /static 引用路径问题
  15. PAT B1023
  16. SpringMVC实现国际化过程中所遇问题
  17. 常见聚类算法——K均值、凝聚层次聚类和DBSCAN比较
  18. javascript避免dom事件重复触发
  19. [Offer收割]编程练习赛13 解题报告
  20. org.springframework.beans.factory.BeanCreationException,Invocation of init method failed,Context initialization failed

热门文章

  1. @EnableAsync使用
  2. Django项目:CRM(客户关系管理系统)--43--35PerfectCRM实现CRM重写Admin密码修改
  3. TZ_13_Hystix的服务降级_线程隔离
  4. 20190828 [ Night ] - 弋
  5. Hibernate中的Query
  6. Pycharm 2018激活(Mac版)
  7. 页面PC端 / 移动端整屏纵向翻页,点击/触摸滑动效果功能代码非插件
  8. C#基础之特性
  9. 洛谷P1965 转圈游戏 [2013NOIP提高组 D1T1][2017年6月计划 数论04]
  10. 洛谷P1147 连续自然数和 [2017年6月计划 数论01]