Number Theory Knowledge Arrangement

1. Fast Power


Find a
b  mod p , where p=1e9+7 .

Problem- solving idea: convert b to binary b=13

13=8+4+1

a b = a 8 + 4 + 1 = a 8 * a 4 * a 1

You can put a 1 time, a 2 times, and a 4 times first. . . . preprocessed

Then convert b to binary, if the i-th bit is 1, then multiply a to the 2 i power.



#include<bits/stdc++.h>
using namespace std;
const int M=1e9+7;
long long a,b;
long long qkpow(long long x,long long y){
	long long ans=1;
	long long bin=x%M;
	while(y!=0){
		if(y&1!=0)ans=(ans*bin)%M;
		bin=(bin*bin)%M;
		y>>=1;
	}
	return ans;
}
int main(){
	cin>>a>>b;
	cout<<qkpow(a,b);
	return 0;
}


Here, bit operations are used for optimization, and the idea is natural.


2. Extended Euclidean Algorithm


Given a, b, find x, y such that ax+by=gcd(a, b)


#include<bits/stdc++.h>
using namespace std;
long long x,y,a,b,d;
void gcd(long long a,long long b,long long& d,long long&x,long long& y){
    if(!b){d=a;x=1;y=0;}
    else{gcd(b,a%b,d,y,x);y-=x*(a/b);}
}
int main(){
    cin>>a>>b;
    gcd(a,b,d,x,y);
    cout<<(x+b)%b;
    return 0;
}

3. Chinese Remainder Theorem

Title description: The title in "Sun Tzu's Suanjing": There are things I don't know how many, A[i] is more than B[i], what is the total number of things?



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730337&siteId=291194637