gcd+lcm
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL gcd(LL a,LL b){
return b==0?a:gcd(b,a%b);
}
LL lcm(LL a,LL b){
return a*b/gcd(a,b);
}
int main(){
int n;
LL a,b;
scanf("%d",&n);
while(n--){
scanf("%lld %lld",&a,&b);
printf("%lld %lld\n",gcd(a,b),lcm(a,b));
}
return 0;
}
分解质因数
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
LL x;
int n;
scanf("%d",&n);
while(n--){
scanf("%lld",&x);
printf("%lld = ",x);
for(int i=2;i*i<=x;i++){
if(x%i==0){
int cnt = 0;
while(x%i==0){
x=x/i;
cnt++;
}
printf("%d",i);
if(cnt>1) printf("^%d",cnt);
if(x!=1) printf(" * ");
}
}
if(x!=1) {
printf("%lld\n",x);
}else if(x==1){
printf("\n");
}
}
return 0;
}
费马小定理+快速幂
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int p=19260817;
LL poww(LL a,LL n,LL p){
LL res = 1;
while(n){
if(n & 1) res = (res * a) % p;
a = (a * a) % p;
n >>= 1;
}
return res;
}
int main(){
int T;
cin>>T;
while(T--){
LL n;
cin>>n;
cout<<poww(n,p-2,p)<<endl;
}
return 0;
}
扩展欧几里得
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL p=19260817;
void exgcd(LL a,LL b,LL &x,LL &y){
if(b == 0){
x = 1;y = 0;
}else{
exgcd(b,a%b,y,x);
y -= (a/b) * x;
}
}
int main(){
int t;
LL x,y;
cin>>t;
while(t--){
LL n;
cin>>n;
exgcd(n,p,x,y);
cout<<(x%p+p)%p<<endl;
//cout<<(x+p)%p<<endl;//或者
//由于扩欧的结果只满足|x|+|y|最小,由题目的要求x为正整数应该输出(x%b+b)%b(由于x+b可能还是小于0)
}
return 0;
}
欧拉函数
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL phi(LL x){
LL ans =x;
for(LL pi=2;pi*pi<=x;pi++){
if(x%pi==0){
ans=(ans/pi)*(pi-1);
while(x%pi==0) x/=pi;
}
}
if(x>1) ans=(ans/x)*(x-1);
return ans;
}
int main(){
int t;
cin>>t;
LL a;
while(t--){
scanf("%lld",&a);
printf("%lld\n",phi(a));
}
return 0;
}
欧拉定理
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL Eular(LL x){
LL phi =x;
for(LL pi=2;pi*pi<=x;pi++){
if(x%pi==0){
phi=(phi/pi)*(pi-1);
while(x%pi==0) x/=pi;
}
}
if(x>1) phi=(phi/x)*(x-1);
return phi;
}
LL gcd(LL a,LL b){
return b==0?a:gcd(b,a%b);
}
LL pow(int a,int x,int mod){
LL ans=1;
for(int i=0;i<x;i++){
ans=ans*a%mod;
}
return ans;
}
int main(){
LL t,a,c,n;
cin>>t;
while(t--){
scanf("%lld%lld%lld",&a,&c,&n);
LL p = Eular(n);
if(gcd(a,n)==1){
printf("%lld\n",pow(a,c%p,n));
}else{
if(c<p){
printf("%lld\n",pow(a,c,n));
}else if(c>=p){
printf("%lld\n",pow(a,c%p+p,n));
}
}
}
return 0;
}