【模板】费马小定理求逆元|快速幂、数论

题目:

P1226 【模板】快速幂 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

下面这道题用费马小定理+快速幂的结论的程序会TLE,且费马小定理需要互质和模数p为质数,

但是可以作为练习 

P3811 【模板】模意义下的乘法逆元 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

参考:

第二十七章 数论——快速幂与逆元_快速幂求逆元csdn-CSDN博客

 

总结成一句结论:当模 p 是质数,且a在模 p 意义下的乘法逆元存在,这个逆元为a^{p-2}(mod p),涉及到幂的计算,使用快速幂计算提高效率。

代码: 

//#include<iostream>
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N=1e3+10;
int a,b,p;

signed main() {
   
    ios::sync_with_stdio(0);
    cout.tie(0);
	cin.tie(0);
  
    cin>>a>>b>>p;
    int bb=b,aa=a;
    int res=1;
    while(b){
    	if(b&1){
    		// 记得取模 
    		//该二进制第i位上为1,乘上a的2的i次方 
    		res=res*a%p;
    		
		}
		// 记得取模 ,a变成原来的平方 a^1-> a^2 ->a^4(2^2)->a^8(2^3)->a^16->a^32.....
    	a=a*a%p;
    	b=b>>1;
	}
   
    cout<<aa<<"^"<<bb<<" mod "<<p<<'='<<res;
    return 0;
}
//#include<iostream>
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N=1e3+10;

//快速幂求a^b并模p 
int qmi(int a,int b,int p) {
	 int res=1;
	 while(b){
	 	if(b&1){
	 		res=res*a%p;
		 }
	 	a=a*a%p;
	 	b=b>>1;
	 } 
	 return res;
}
signed main() {
   
    ios::sync_with_stdio(0);
    cout.tie(0);
	cin.tie(0);
  
    int n,p;
    cin>>n>>p;
    int t=1;
    while(t<=n){
    	cout<<qmi(t,p-2,p)<<endl;
    	t++;
	}
   
   
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guts350

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值