一、试除法求约数
#define _CRT_SECURE_NO_WARNINGS//解决scanf不安全问题
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <cmath>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef double db;
#define lowbit(x) ((x) & -(x))//找到x的二进制数的最后一个1
#define inf 0x3f3f3f3f
vector<int> foo(int x)
{
vector<int>cnt;
for (int i = 1; i <= x / i; i++)
{
if (x % i == 0)
{
cnt.push_back(i);
if (i != x / i)
{
cnt.push_back(x / i);
}
}
}
sort(cnt.begin(), cnt.end());
return cnt;
}
int main()
{
std::ios::sync_with_stdio(0);
int n;
cin >> n;
while (n--)
{
int x;
cin >> x;
auto res = foo(x);
for (auto t : res)
{
cout << t << " ";
}
cout << endl;
}
return 0;
}
二、约数个数
(P[k]为质数)
约数个数:
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
ll ans=1;
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]++;
}
for(auto prime:primes)
{
ans=ans*(prime.second+1)%mod;
}
cout<<ans<<endl;
return 0;
}
三、约数之和
(P[k]为质数)
约数之和:
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
typedef long long ll;
int n;
const int mod = 1e9+7;
int main()
{
cin>>n;
unordered_map<int,int>primes;
while(n--)
{
int a;
cin>>a;
for(int i=2;i<=a/i;i++)
{
while(a%i==0)
{
a/=i;
primes[i]++;
}
}
if(a>1)
{
primes[a]++;
}
}
ll ans=1;
for(auto prime:primes)
{
int p=prime.first,x=prime.second;
ll s=1;
for(int i=1;i<=x;i++)
{
s=(s*p+1)%mod;
}
ans=ans*s%mod;
}
cout<<ans<<endl;
return 0;
}
四、欧几里得算法(辗转相除法)
核心原理:
if(d%a==0&&d%b==0) 那么d%(a+b)==0或者d%(a*x+b*y)==0
gcd(a,b)==gcd(b,a mod b);
#define _CRT_SECURE_NO_WARNINGS//解决scanf不安全问题
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <string>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
typedef double db;
#define lowbit(x) ((x) & -(x))//找到x的二进制数的最后一个1
#define inf 0x3f3f3f3f
int gcd(int a, int b)
{
return b != 0 ? gcd(b, a % b) : a;
}
int main()
{
std::ios::sync_with_stdio(0);
int n;
cin >> n;
while (n--)
{
int a, b;
cin >> a >> b;
cout << gcd(a, b) << endl;
}
return 0;
}