码迷,mamicode.com
首页 > 其他好文 > 详细

ACM1005:Number Sequence

时间:2019-03-13 00:09:00      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:nbsp   com   scan   clu   follow   signal   test   ane   esc   

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>
#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

ACM1005:Number Sequence

标签:nbsp   com   scan   clu   follow   signal   test   ane   esc   

原文地址:https://www.cnblogs.com/mycodinglife/p/10520305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!