洛谷 P1075 [NOIP2012 普及组] 质因数分解
思路:算数基本定理,约数个数定理
质因数分解
//N太大,long long装不下
#include<iostream>
using namespace std;
int primes[10010] = {0};
int main()
{
int n;
cin >> n;
for(int i = 2 ; i <= n ; i++)
{
int i1 = i;
for(int j = 2 ; j <= i ; j++)
{
while(i1%j == 0)
{
i1 /= j;
primes[j]++;
}
}
}
for(int i = 1 ; i <= 10000 ; i++)
{
if(primes[i] > 0)
{
cout << i << " " << primes[i] << endl;
}
}
return 0;
}
洛谷 P5736 【深基7.例2】质数筛
暴力
//解法1
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int a[110]={0};
int n;
cin >> n;
int i,j,temp;
for(i=1;i<=n;i++)
{
cin >> temp;
for(j=2;j<=(int)sqrt(temp);j++)
if(temp%j==0) break;
if(temp==0||temp==1) continue;
if(j>(int)sqrt(temp)) a[i]=temp;
}
for(i=1;i<=n;i++)
if(a[i]!=0) cout << a[i] << " ";
return 0;
}
欧拉筛
//解法2
#include<iostream>
using namespace std;
bool st[100010];
int primes[100010];
int cnt = 0;
void get_primes(int n) //欧拉筛
{
st[1] = true;
for(int i = 2 ; i <= n ; i++)
{
if(!st[i])
{
primes[++cnt] = i;
}
for(int j = 1 ; j <= cnt && i * primes[j] <= n ; j++)
{
st[i * primes[j]] = true;
if(i % primes[j] == 0) break;
}
}
}
int main()
{
get_primes(100000);
int n;
cin >> n;
int temp;
while(n--)
{
cin >> temp;
if(!st[temp])
{
cout << temp << " ";
}
}
return 0;
}
裴蜀定理
定义
若a,b属于整数,且a,b的最大公约数 gcd(a , b) = d,那么对于任意的x,y属于整数,都有:ax + by 都一定是 d 的倍数。
特别地,一定存在x,y属于整数,使得 ax + by = d 成立。
设 d|gcd(a , b),那么说明 d|a,d|b,对于任意的x,y属于整数,都有 d|(ax + by)
2元
裴蜀定理:一定存在整数x,y。使得:ax + by = gcd(a , b) 成立;
裴蜀定理推广:任意的x,y属于整数,都有:ax + by = gcd(a , b) * n;
推论:对于方程ax + by = 1,只有当整数a,b互质时,方程才有整数解。
a,b 互质的充要条件:方程ax + by = 1 有整数解。
判断二元不定方程是否有整数解的方法:对于方程 ax + by = z,只有满足 gcd(a , b) | z,方程才有整数解。
推广到n元
裴蜀定理(n元):一定存在整数x1 , x2 , … , xn。使得:a1x1 + a2x2 + … + anxn= gcd(a1 , a2 , … , an) 成立;
裴蜀定理推广(n元):任意的x1 , x2 , … , xn属于整数,都有:a1x1 + a2x2 + … + anxn= gcd(a1 , a2 , … , an) * n;
推论(n元):对于方程a1x1 + a2x2 + … + anxn= 1,只有当整数a1 , a2 , … , an的最大公约数为1(互质)时,方程才有整数解。
a1 , a2 , … , an 互质的充要条件(n元):方程a1x1 + a2x2 + … + anxn= 1有整数解。
判断n元不定方程是否有整数解的方法:对于方程 a1x1 + a2x2 + … + anxn= z,只有满足 gcd(a1 , a2 , … , an) | z,方程才有整数解。