试除法判断质因数
原理:
若a能被b整除,则a也可被(a/b)整除,例如18可以被3整除,同时也可以被6整除。
代码:
bool solve(int x)
{
if(x<2) return false;
for(int i=2;i<x;i++)
{
if(x%i==0) return false;
}
return true;
}
优化后的代码:
bool solve(int x)
{
if(x<2) return false;
for(int i=2;i<=x/i;i++)
{
if(x%i==0) return false;
}
return true;
}
分解质因数
题目描述:
给定 n 个正整数 a i a_{i} ai,将每个数分解质因数,并按照质因数从小到大的顺序输出每个质因数的底数和指数。
题解:
试除法判断一个数是否是 a i a_{i} ai的质因数
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
void solve(int x)
{
map<int,int> st;
for(int i=2;i<=x/i;i++)
{
while(x%i==0)
{
st[i]++;
x/=i;
}
}
if(x>1) st[x]++;
for(auto t:st) cout<<t.first<<" "<<t.second<<endl;
cout<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int x;
cin>>x;
solve(x);
}
return 0;
}
筛质数
1.最朴素的筛法
原理:
若一个数是另一个数的倍数的话,则这个数肯定不是质数,所以对于每个数将他的倍数删去。
代码:
bool{
int cnt=0;
for(int i=2;i<=x;i++)
{
if(!st[i]) primes[cnt++]=i;
for(int j=2*i;j<=x;j+=i)//把一个数的倍数打上标记
{
st[j]=true;
}
}
}
2.埃氏筛法
原理:
可以用质数的倍数删去所有合数。
bool solve(int x)
{
int cnt=0;
for(int i=2;i<=x;i++)
{
if(!st[i])
{
primes[cnt++]=i;
for(int j=2*i;j<=x;j+=i) st[j]=true;//只需将合数的倍数删去即可
}
}
}
3.线性筛:
在埃氏筛法中一个数可以被多次删去,例如8,会被2删去,同时也会被4删去
原理:
每次用n的最小质因数删去n。
代码:
bool solve(int x)
{
int cnt=0;
for(int i=2;i<=x;i++)
{
if(!st[i]) primes[cnt++]=i;
for(int j=0;primes[j]<=x/i;j++)
{
st[primes[j]*i]=true;
if(i%primes[j]==0) break;
}
}
}
试除法求约数
原理:
若n可以被a整除,则n可以被(n/a)整除,所以通过一次判断可以得出两个约数。
代码:
void solve(int x)
{
int cnt=0;
for(int i=1;i<=x/i;i++)
{
if(x%i==0)
{
st[cnt++]=i;
if(i!=x/i) st[cnt++]=x/i;
}
}
sort(st,st+cnt);
for(int i=0;i<cnt;i++) cout<<st[i]<<" ";
cout<<endl;
}
约数个数
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const int mod = 1e9 + 7;
int main(){
int n,x;
LL ans = 1;
unordered_map<int,int> hash;
cin >> n;
while(n--){
cin >> x;
for(int i = 2;i <= x/i; ++i){
while(x % i == 0){
x /= i;
hash[i] ++;
}
}
if(x > 1) hash[x] ++;
}
for(auto i : hash) ans = ans*(i.second + 1) % mod;
cout << ans;
return 0;
}
约数之和
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long LL;
const int N = 110, mod = 1e9 + 7;
int main()
{
int n;
cin >> n;
unordered_map<int, int> primes;
while (n -- )
{
int x;
cin >> x;
for (int i = 2; i <= x / i; i ++ )
while (x % i == 0)
{
x /= i;
primes[i] ++ ;
}
if (x > 1) primes[x] ++ ;
}
LL res = 1;
for (auto p : primes)
{
LL a = p.first, b = p.second;
LL t = 1;
while (b -- ) t = (t * a + 1) % mod;
res = res * t % mod;
}
cout << res << endl;
return 0;
}
最大公约数
原理:
gcd(a,b)=gcd(a,a%b)。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int T;
cin >> T;
while(T--)
{
int a, b;
cin >> a >> b;
//辗转相除,直到小括号内右边数为0
while(b)
{
//c 一定小于 b
int c = a % b;
//小括号左边放除数,右边放约数
a = b;
b = c;
}
//小括号内左边数为最大公约数
cout << a << endl;
}
}