数论学习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;
        }
    }
}
相关推荐
个 人 练 习 生3 分钟前
C++ string 类模拟实现:从底层理解字符串(上)
开发语言·c++·经验分享·学习·程序人生
垆边人似月.11 分钟前
华为机试题 :有效的括号
c++·算法·华为
坤坤子吖15 分钟前
C++智能指针:RAII、shared_ptr与内存泄漏
开发语言·c++·笔记·学习
A加ITIL教练长河achotsao1 小时前
ITIL Master 战略领导者课后系列分享:AI编程正在重新划分研发与运维的边界
算法
hahaha60161 小时前
FPGA+ARM实现AWB的全流程
人工智能·嵌入式硬件·算法·计算机视觉·fpga开发
李洱1 小时前
LangChain 和 LangGraph 的区别:核心原理与使用场景
算法
夏幻灵1 小时前
每日一题:LeetCode 206:反转链表——三指针与原地反转详解
算法·leetcode·链表
CQU_JIAKE1 小时前
10.9【A】
数据结构
第25小时记录1 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·python