算法----约数
前言
继国缘一:凡登峰造极者,必殊途同归。
提示:以下是本篇文章正文内容,下面案例可供参考
一、试除法求约数
给定 n
个正整数 ai
,对于每个整数 ai
,请你按照从小到大的顺序输出它的所有约数。
输入格式
第一行包含整数 n
。
接下来 n
行,每行包含一个整数 ai
。
输出格式
输出共 n
行,其中第 i
行输出第 i
个整数 ai
的所有约数。
数据范围
1≤n≤100
,
1≤ai≤2×109
输入样例:
2
6
8
输出样例:
1 2 3 6
1 2 4 8
就是板子,背就完事了!
但是!要注意的是,这个的for循环是i从1开始的,很特殊!
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
void yueshu(int n)
{
vector<int>res;
for(int i=1;i<=n/i;i++)
{
if(n%i==0)
{
res.push_back(i);
if(i!=n/i) res.push_back(n/i);
}
}
sort(res.begin(),res.end());
for(auto item:res)
{
cout<<item<<" ";
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int x;
cin>>x;
yueshu(x);
}
return 0;
}
二、约数个数
上图有公式,根据公式写板子
代码如下(示例):
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;
const int N = 110,mod=1e9+7;
typedef long long LL;
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)
{
res=res*(p.second+1)%mod;
}
cout<<res<<endl;
return 0;
}
三…约数之和
代码如下(示例):
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;
const int N = 110,mod=1e9+7;
typedef long long LL;
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;
}
四…最大公约数
这个求最大公约数真就背就行了
return b?o(b,a%b):a;就这个!!
#include<iostream>
using namespace std;
int o(int a,int b)
{
return b?o(b,a%b):a;
}
int main()
{
int a,b,n;
cin>>n;
while(n--)
{
cin>>a>>b;
cout<<o(a,b)<<endl;
}
return 0;
}
总结
提示:这里对文章进行总结:约数的基本用法,基本上全靠背!加油!!