【无标题】

算法----约数

前言

继国缘一:凡登峰造极者,必殊途同归。


提示:以下是本篇文章正文内容,下面案例可供参考

一、试除法求约数

给定 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;
}

总结

提示:这里对文章进行总结:约数的基本用法,基本上全靠背!加油!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值