数论学习1

矩阵快速幂

求矩阵a的k次方:

cpp 复制代码
struct mat{
    ll c[101][101];
    mat(){
        memset(c,0,sizeof(c));
    }
} a, res;

ll n,k;

// 重载运算符,矩阵乘法
mat operator*(mat &x,mat &y){
    mat t;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            for(int k=1;k<=n;k++){
                t.c[i][j]=(t.c[i][j]+x.c[i][k]*y.c[k][j])%MOD;
            }
        }
    }
    return t;
}

void qpow(ll k){
    for(int i=1;i<=n;i++) res.c[i][i]=1; //单位矩阵
    while(k){
        if(k&1) res=res*a;
        a=a*a;
        k>>=1;
    }
}

void solve(){
    cin>>n>>k;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>a.c[i][j];
        }
    }
    qpow(k);

    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cout<<res.c[i][j]<<" \n"[j==n];
        }
    }
}

矩阵加速递推

代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define i128 __int128_t
#define INF -1e18
#define ls(x) x<<1
#define rs(x) x<<1|1
#define pii pair<int,int>
#define lowbit(x) ((x)&-(x))
#define IOS ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
#define fi first
#define se second
#define endl '\n'
typedef long long ll;
const int N=10001;
const int M=1000000;
const int MOD=1e9+7;
const int maxk=22;

struct mat{
    ll c[3][3];
    mat(){
        memset(c,0,sizeof(c));
    }
}F,A;

mat operator*(mat &a,mat &b){
    mat t;
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            for(int k=1;k<=2;k++){
                t.c[i][j]=(t.c[i][j]+a.c[i][k]*b.c[k][j])%MOD;
            }
        }
    }
    return t;
}

void qpow(int k){
    F.c[1][1]=F.c[1][2]=1;
    A.c[1][1]=A.c[1][2]=A.c[2][1]=1;
    while(k){
        if(k&1) F=F*A;
        A=A*A;
        k>>=1;
    }
}

void solve(){
    int n;
    cin>>n;
    if(n<=2){
        cout<<1<<endl;
        return;
    }
    qpow(n-2);
    cout<<F.c[1][1]<<endl;
}

signed main(){
    IOS;
    int T=1;
    //cin>>T;
    while(T--){
        solve();
    }

    return 0;
}

分解质因数

代码:

cpp 复制代码
int n;
int a[10001]; //质因数的个数

//分解质因数
void op(int x){
    for(int i=2;i*i<=x;i++){
        while(x%i==0){
            a[i]++;
            x/=i;
        }
    }
    if(x>1) a[x]++;
}

void solve(){
    cin>>n;
    for(int i=2;i<=n;i++){
        op(i);
    }
    for(int i=1;i<=n;i++){
        if(a[i]){
            cout<<i<<" "<<a[i]<<endl;
        }
    }
}
相关推荐
.道阻且长.4 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC6 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
白狐_7986 小时前
408数据结构第5章:二叉树遍历序列题——技巧、判断与真题型总结
数据结构
Forever Nore9 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR10 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
圆奋奋10 小时前
FreeRTOS学习(三)- 任务调度模块
学习·开源·freertos
吃着火锅x唱着歌11 小时前
Effective C++ 学习笔记 条款40 明智而审慎地使用多重继承
c++·笔记·学习
Tisfy11 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
xian_wwq11 小时前
【学习笔记】Prompt Engineering 没死,只是它不再够用了-2/16
笔记·学习·prompt