ACM1005: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).
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
------------------------------------------------------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | #include<stdio.h> #include<string.h> #define SIZE 2 long long int ** multiple( long long int a[][SIZE], long long int b[][SIZE]); int main() { int A, B; long long int n; long long int factor[SIZE][SIZE]; long long int ans[SIZE][SIZE]; while ( scanf ( "%d%d%lld" , &A, &B, &n) && (A||B||n)) { memset (factor, 0, 2 * 2 * sizeof ( int )); memset (ans, 0, 2 * 2 * sizeof ( int )); factor[0][0] = A; factor[0][1] = B; factor[1][0] = 1; factor[1][1] = 0; //矩阵快速幂 for ( int i = 0; i < SIZE; i++) ans[i][i] = 1; n = n - 2; while (n > 0) { if (n & 1) memcpy (ans, multiple(ans, factor), 2 * 2 * sizeof ( long long int )); memcpy (factor, multiple(factor, factor), 2 * 2 * sizeof ( long long int )); n >>= 1; } printf ( "%lld\n" , (ans[0][0] + ans[0][1]) % 7); } return 0; } long long int ** multiple( long long int a[][SIZE], long long int b[][SIZE]) { int i, j, k; long long int c[SIZE][SIZE]; memset (c, 0, 2 * 2 * sizeof ( long long int )); for (i = 0; i < SIZE; i++) for (j = 0; j < SIZE; j++) for (k = 0; k < SIZE; k++) { c[i][j] += a[i][k] * b[k][j]; c[i][j] = c[i][j] % 7; } return c; } |
参考文章:
https://blog.csdn.net/codeswarrior/article/details/81258928
https://www.cnblogs.com/cmmdc/p/6936196.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:使用 .NET 为树莓派开发 Wifi 配网功能
· C# 模式匹配全解:原理、用法与易错点
· 记一次SSD性能瓶颈排查之路——寿命与性能之间的取舍
· 理解 .NET 结构体字段的内存布局
· .NET 9中的异常处理性能提升分析:为什么过去慢,未来快
· C# 模式匹配全解:原理、用法与易错点
· 杂七杂八系列----C#代码如何影响CPU缓存速度?
· C#/.NET/.NET Core优秀项目和框架2025年5月简报
· 鸿蒙仓颉语言开发实战教程:商城应用个人中心页面
· FFmpeg开发笔记(六十三)FFmpeg使用vvenc把视频转为H.266编码