问题 I: 【数论】普通递归关系

代码一
这个就是矩阵快速幂, 然后第一次WA了, 因为没用double , 我不知道为啥用double, 然后题目要求就是四舍五入啥的, 所以用了之后就对了

#include <iostream>
using namespace std;
typedef long long ll ;
struct node
{
	double a[3][3] ;
};
node mul(node x , node y)
{
	node res ;
	for(int i = 0 ;i < 2 ;i ++)
	 for(int j = 0 ;j < 2 ;j ++)
	  {
	  	res.a[i][j] = 0 ;
	  	for(int k = 0 ;k < 2 ;k ++)
	  	 res.a[i][j] = res.a[i][j] + x.a[i][k] * y.a[k][j] ;
	  }
	return res ;
}
node qmi(node a , int b)
{
	node res ;
	for(int i = 0 ;i < 2 ;i ++ )
	 for(int j = 0 ;j < 2 ;j ++)
	  if(i == j)
	   res.a[i][j] = 1;
	  else res.a[i][j] = 0 ;
	while(b)
	{
		if(b & 1) res = mul(res , a) ;
		a = mul(a , a) ;
		b >>= 1 ;
	}
	return res ;
}
int main()
{
	double f0 , f1 , a , b , n ;
	double  ans = 0 ;
	node res ;
	cin >> f0 >> f1 >> a >> b >> n ;
	if(f1 == 0 && f0 == 0) cout << 0 << endl ;
	else if(n == 0) printf("%.0lf\n" , f0) ;
	else if(n == 1) printf("%.0lf\n" , f1) ;
	else 
	 {
	 	res.a[0][0] = a , res.a[0][1] = 1 , res.a[1][0] = b , res.a[1][1] = 0 ;
	 	res = qmi(res , n - 1) ;
	 	printf("%.0lf\n" , f1 * res.a[0][0] + f0 * res.a[1][0]) ;
	 }
	return 0 ;
}

代码二
用最普通的递推公式,直接求出来了,
在这里插入图片描述
还有一个点就是在使用k^n, 时 , 因为是double 型, 所以就不能使用快速幂, 只能用递推来处理这个

#include <iostream>
#include <cmath>
using namespace std;
double s(double a , int b)
{
    if(b == 0) return 1 ;
    double k = s(a , b / 2) ;
    if(b % 2 == 0)
     return k * k ;
    else return k * k * a ; 
}
int main()
{
    double f0 , f1 , a , b , n , ans = 0;
    cin >> f0 >> f1 >> a >> b >> n ;
    double k = (a - sqrt(a * a + 4 * b) )/ 2 ;
    double m = (a + sqrt(a * a + 4 * b) )/ 2 ;
    if(f0 == 0 && f1 == 0)
     cout << 0 << endl ;
    else
     {
        ans = (s(k , n) * (f1 - m * f0) - s(m , n) * (f1 - k * f0)) / (k - m) ;
        printf("%.0lf\n" , ans) ;
     }
     return 0 ;
}
posted @ 2019-10-09 16:19  spnooyseed  阅读(118)  评论(0编辑  收藏  举报