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种组合后必定循环
}
}
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种组合后必定循环
}
}
相关文章推荐
- HDU 1005 Number Sequence【循环节】
- HDU 1005 Number Sequence
- hdu-1005 Number Sequence
- HDU-1005 Number Sequence
- HDU 1005 Number Sequence
- HDU 1005 Number Sequence(循环周期是关键)
- HDU 1005 Number Sequence
- HDU 1005 Number Sequence[数论]
- hdu 1005 Number Sequence(思维题)
- hdu 1005 Number Sequence
- HDU 1005 Number Sequence (寻找循环节)
- HDU 1005 Number Sequence
- HDU 1005 Number Sequence
- HDU 1005 Number Sequence
- HDU_1005 Number Sequence
- hdu 1005 Number Sequence 构造矩阵 + 矩阵快速幂
- hdu 1005 Number Sequence
- hdu 1005 Number Sequence
- HDU 1005 Number Sequence
- ACM_HDU 1005 Number Sequence