杭电OJ 1005 Number Sequence

本文探讨了一种解决大规模数列求值问题的有效方法。通过对数列规律的深入分析,提出了利用周期性优化递归算法的策略,避免了内存溢出问题,显著提高了计算效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 212774    Accepted Submission(s): 53788


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


错误思路:递归

一开始看这道题,想都没想直接函数递归,VS上跑的不亦乐乎,样本测试用例都通过了,欸心想肯定过,拿到OJ上提交,显示内存溢出,眉头一皱发现事情并不简单,仔细分析,n可能是一个超大的数,当数很大时,函数递归的深度不可想象,把n换成大数果然,VS上也出现了栈溢出,先把错误代码po出来

#include<math.h>
#include<iostream>
#include<string.h>
using namespace std;

long long f(long long n,int A,int B)
{
	long long result;
	if (n == 1 || n == 2)
		return 1;
	else
	{
		result = (A*f(n - 1,A,B) + B * f(n - 2,A,B)) % 7;
		return result;
	}
}
int main() {
	int A, B;
	long long n;
	while (cin >> A >> B >> n)
	{
		if (A == 0 && B == 0 && n == 0)
			return 0;
		if (A >= 1 && A <= 1000 && B >= 1 && B <= 1000 && n >= 1 && n <= 100000000)
		{
			cout << f(n,A,B)<<endl;
		}
	}
	return 0;
}

正确思路:如题所述,发现数的顺序规律

仔细观察所给函数可以发现,无论f(n)怎么变,最终取模7后的答案,结果一定是[0,6],这个地方理解到很重要;也就是说,f(n-1)和f(n-2)的范围同样是在[0,6],那么当n>2时,两两组合得到的f(n)会有7*7=49种不同的答案,即结果取值会是49种一周期,之后所有的结果都会从者49种结果中产生,那么新代码的思路也就出来了,只需要将前49种结果都算出来,最后匹配n%49传参即可得到正确答案。

#include<math.h>
#include<iostream>
#include<string.h>
using namespace std;

int f(int n,int A,int B)
{
	int result;
	if (n == 1 || n == 2)
	{
		return 1;
	}
	else
	{
		result= (A*f(n - 1, A, B) + B * f(n - 2, A, B)) % 7;
		return result;
	}
}
int main() {
	int A, B;
	long n;
	while (cin >> A >> B >> n)
	{
		if (A == 0 && B == 0 && n == 0)
			return 0;
		if (A >= 1 && A <= 1000 && B >= 1 && B <= 1000 && n >= 1 && n <= 100000000)
		{
			cout << f((n%49),A,B)<<endl;
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值