您的位置:首页 > 产品设计 > UI/UE

hdu 1005 Number Sequence

2018-02-16 20:48 459 查看
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).
这道题递归不做任何优化就会stackoverflow,这道题是mod7,又是个递归公式,想到f(n)与f(n-1)和f(n-2)的有着关系,很容易想的f(n-1)和f(n-2)在7*7=49种不同的两两组合计算后会出现相同的情况,故用n%49对其优化:#include<iostream>
using namespace std;
int a,b;
int f(int n)
{
if(n==1||n==2)
return 1;
else
return (a*f(n-1)+b*f(n-2))%7;
}
void main()
{
int n;
while(cin>>a>>b>>n&&(a||b||n))
{
cout<<f(n%49)<<endl;//7*7=49种组合后必定循环
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: