pell数列题解--递归超时优化

描述

Pell数列a1, a2, a3, ...的定义是这样的,a1 = 1, a2 = 2, ... , an = 2 * an − 1 + an - 2 (n > 2)。
给出一个正整数k,要求Pell数列的第k项模上32767是多少。

输入

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数k (1 ≤ k < 1000000)。

输出

n行,每行输出对应一个输入。输出应是一个非负整数。

样例输入

2 1 8 样例输出
1 408

递归:

#include<iostream>
using namespace std;
const int M = 32767;

int ANum(int num)
{
	if (num == 1)
		return 1;
	else if (num == 2)
		return 2;
	else
		return 2 * ANum(num - 1) + ANum(num - 2);

}
int main()
{
	int  a,num,a_num;
	cin >> a;
	while (a--)
	{
		cin >> num;
		a_num = ANum(num);
		cout << ANum << endl;
	}


	return 0;
}

非递归:

#include<iostream>
using namespace std;
const int M = 32767;
int b[1000000];//大数组定义在外边
int main()
{
    int  a, num, a_num;
    cin >> a;
    while (a--)
   {
	cin >> num;
	b[1] = 1;
	b[2] = 2;	
	if(num != 1&&num != 2)
	{
		for (int i = 3; i <= num; i++)
		{
			b[i] = (2 * b[i - 1] + b[i - 2])%M;//数组中直接存求模后的值,不然很可能会超出int类型数据的范围。
		}
	}
	cout << b[num] << endl;
}
return 0;
}

非递归优化:

#include<iostream>
using namespace std;
const int M = 32767;

int main()
{
    int  a, num, a_num,b1,b2,b3;
    cin >> a;
    while (a--)
   {
	cin >> num;
	b1 = 1;
	b2 = 2;	
	if(num != 1&&num != 2)
	{
		for (int i = 3; i <= num; i++)
		{
			b3 = (2 * b2 + b1)%M;//数组中直接存求模后的值,不然很可能会超出int类型数据的范围。
            b1=b2;
            b2=b3;

		}
	}
	cout << b[num] << endl;
}
return 0;
}

注:优化借鉴 CSDN博主「时雨乍停」的原创文章

原文链接:https://blog.csdn.net/qq_45697327/article/details/126609258

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值