數論 - 約數 - 試除法求約數 + 約數個數 + 約數之和 + 最大公約數
1、 試出法求約數
給定n個正整數ai,對於每個整數ai,請你按照從小到大的順序輸出它的所有約數。
輸入格式
第一行包含整數n。
接下來n行,每行包含一個整數ai。
輸出格式
輸出共n行,其中第 i 行輸出第 i 個整數ai的所有約數。
數據範圍
1≤n≤100,
2≤ai≤2∗109
輸入樣例:
2
6
8
輸出樣例:
1 2 3 6
1 2 4 8
分析:
代碼:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int N=110;
int n;
void solve(int x)
{
vector<int> p;
for(int i=1;i<=x/i;i++)
if(x%i==0)
{
p.push_back(i);
if(i!=x/i) p.push_back(x/i);
}
sort(p.begin(),p.end());
for(int i=0;i<p.size();i++) cout<<p[i]<<' ';
cout<<endl;
}
int main()
{
cin>>n;
while(n--)
{
int x;
cin>>x;
solve(x);
}
return 0;
}
2、約數個數
給定n個正整數ai,請你輸出這些數的乘積的約數個數,答案對109+7取模。
輸入格式
第一行包含整數n。
接下來n行,每行包含一個整數ai。
輸出格式
輸出一個整數,表示所給正整數的乘積的約數個數,答案需對109+7取模。
數據範圍
1≤n≤100,
1≤ai≤2∗109
輸入樣例:
3
2
6
8
輸出樣例:
12
具體落實:
代碼:
#include<iostream>
#include<unordered_map>
#define ll long long
#define x first
#define y second
using namespace std;
const int mod=1e9+7;
int n;
unordered_map<int,int> P;
int main()
{
cin>>n;
while(n--)
{
int x;
cin>>x;
for(int i=2;i<=x/i;i++)
while(x%i==0)
{
x/=i;
P[i]++;
}
if(x>1) P[x]++;
}
ll res=1;
for(auto p: P)
res=res*(p.y+1)%mod;
cout<<res<<endl;
return 0;
}
3、約數之和
給定n個正整數ai,請你輸出這些數的乘積的約數之和,答案對109+7取模。
輸入格式
第一行包含整數n。
接下來n行,每行包含一個整數ai。
輸出格式
輸出一個整數,表示所給正整數的乘積的約數之和,答案需對109+7取模。
數據範圍
1≤n≤100,
1≤ai≤2∗109
輸入樣例:
3
2
6
8
輸出樣例:
252
具體落實:
代碼:
#include<iostream>
#include<unordered_map>
#define ll long long
#define x first
#define y second
using namespace std;
const int mod=1e9+7;
int n;
unordered_map<int,int> prime;
int main()
{
cin>>n;
while(n--)
{
int x;
cin>>x;
for(int i=2;i<=x/i;i++)
while(x%i==0)
{
x/=i;
prime[i]++;
}
if(x>1) prime[x]++;
}
ll res=1;
for(auto p : prime)
{
ll t=0;
for(int i=0;i<=p.y;i++)
t=(t*p.x+1)%mod;
res=res*t%mod;
}
cout<<res<<endl;
return 0;
}