Fibonacci

17 篇文章 0 订阅
6 篇文章 0 订阅

这里写图片描述这里写图片描述这里写图片描述
###题目大意:
算第n个斐波那契数
###解题思路:
根据题意来看就是一个矩阵快速幂的模板题,利用脑海中残留的快速幂知识然而忘了怎么算矩阵乘法,于是用人类最原始的暴力思维一个个枚举算了。。。所幸只是一个2×2的矩阵,然而还是算错了几步调试了半天。。还是要提高姿势水平啊。
暴力代码如下:

#include<iostream>
#include<cstdio>
#include<fstream>
#include<set>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#include<cstdlib>
#include<list>
#include<queue>
#include<stack>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MOD 1000000007
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define meminf(a) memset(a,inf,sizeof(a))
//vector ::iterator it;
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
ll martix[2][2];
void marcount()
{
  ll a2=martix[0][0],b2=martix[0][1],c2=martix[1][0],d2=martix[1][1];
  martix[0][0]=(a2*a2+b2*c2)%10000;
  martix[0][1]=(a2*b2+b2*d2)%10000;
  martix[1][0]=(c2*a2+d2*c2)%10000;
  martix[1][1]=(c2*b2+d2*d2)%10000;
}
ll quickpower(int n)
{
  ll ans[2][2]={{1,0},{0,1}};
  while(n)
  {
    if(n&1)
    {
      ll a1=ans[0][0],b1=ans[0][1],c1=ans[1][0],d1=ans[1][1];
      ans[0][0]=(a1*martix[0][0]+b1*martix[1][0])%10000;
      ans[0][1]=(a1*martix[0][1]+b1*martix[1][1])%10000;
      ans[1][0]=(c1*martix[0][0]+d1*martix[1][0])%10000;
      ans[1][1]=(c1*martix[0][1]+d1*martix[1][1])%10000;
    }
    marcount();
    n/=2;
  }
  return ans[0][1];
}
int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  //freopen("test.txt","r",stdin);
//  freopen("output.txt","w",stdout);
 int n;
 while(cin>>n&&n!=-1)
 {
   if(n==0)cout<<0<<endl;
   else
   {
     martix[0][0]=1;
     martix[0][1]=1;
     martix[1][0]=1;
     martix[1][1]=0;
     ll sum=quickpower(n)%10000;
     cout<<sum<<endl;
   }
 }
 return 0;
}

放个正规的标程吧,利用结构体算矩阵。

#include <iostream>
using namespace std;
const int num = 2;
const int mod = 10000;
struct mat 
{
	int m[num][num];
};

mat I
{
	1,0,
	0,1
};

mat mul(mat a, mat b) 
{
	mat ans;
	for(int i=0;i<num;i++)
		for (int j = 0; j < num; j++) 
    {
			ans.m[i][j] = 0;
			for (int k = 0; k < num; k++)
				ans.m[i][j] += (a.m[i][k] * b.m[k][j]);
			ans.m[i][j] %= mod;
		}
	return ans;
}

mat quick_pow(mat a, long long b) 
{
	mat ans = I;
	mat tmp = a;
	while (b > 0)
   {
		if (b & 1)
			ans = mul(ans, tmp);
		tmp = mul(tmp, tmp);
		b >>= 1;
	}
	return ans;
}

int main() 
{
	long long n;
	mat a
  {
		1,1,
		1,0
	};
	while (cin >> n&&n!=-1) 
  {
		mat tmp;
		tmp = quick_pow(a, n);
		cout << tmp.m[0][1] << endl;
	}
	return 0;
}

大佬初始化矩阵的方式就是骚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值