算法学习——数学知识

快速幂

用二进制的处理方式

#include<iostream>
using namespace std;
typedef unsigned long long ull;


ull qmi(int a,int k,int p)
{
    int res=1;
    while(k)
    {
        if(k&1)res=(ull)res*a%p;//k末尾
        k>>=1;//k移位
        a=(ull)a*a%p;//a更新
    }
    return res;
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int a,k,p;
        cin.tie(0);
        ios::sync_with_stdio(false);
        cin>>a>>k>>p;
        cout<<qmi(a,k,p)<<endl;
    }
    return 0;
}

求组合数

方法一:递推法

关键公式:

C(n,0)=1

2000

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int MOD=1e9+7;
const int N = 2010;
int c[N][N];
void init()
{
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<=i;j++)
        {
            if(j==0)c[i][j]=1;
            else c[i][j]=(c[i-1][j]+c[i-1][j-1])%MOD;
        }
    }
}

int T;
int main()
{
    init();
    cin>>T;
    while(T--)
    {
        int n,m;
        scanf("%d%d", &n, &m);
        printf("%d\n",c[n][m]);
    }
    
    return 0;
}

递推的一个例子211. 计算系数 - AcWing题库

这个数据范围比较小

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1010, MOD = 10007;

int a, b, k, n, m;
int C[N][N];

int main()
{
    scanf("%d%d%d%d%d", &a, &b, &k, &n, &m);

    for (int i = 0; i <= k; i ++ )
        for (int j = 0; j <= i; j ++ )
            if (!j) C[i][j] = 1;
            else C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD;

    int res = C[k][n];
    a %= MOD, b %= MOD;//这里的a m b n不能分开取模,如果分开取模,结果是错的
    for (int i = 0; i < n; i ++ ) res = res * a % MOD;
    for (int i = 0; i < m; i ++ ) res = res * b % MOD;

    printf("%d\n", res);
    return 0;
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值