SDNUOJ 1354.Cut the Cable(求多个数的最大公因数)

博客围绕电缆切割问题展开,给定n条长度不一的长电缆,要将其切割成等长的短电缆且不浪费,需计算短电缆的最长长度及数量。还介绍了求多个数最大公因数的方法,可用辗转相除法,给出了代码思路。

Time Limit: 1000 MS Memory Limit: 32768 KB

Description
The company have n(n<=100) long cables(the length is not necessarily the same),we assume that the length of every long cable is an integer and not exceeded 10000 meters. Now we cut them into short cables with the same length. We are required not to waste every long cable and the length of the short cable is the longer the better. Please calculate the longest length of short cable and how many short cables after cutting.

Input
The input contains two lines.
The first line is n, represents the number of long cables.
The second line has n positive integers separated by spaces, represent the length of long cable.

Output
The first line represent the longest length of short cable.
The second line represent the number of short cables.

Sample Input
4
18 12 24 30

Sample Output
6
14

求俩数的最大公因数可以用辗转相除法(自己写gcd函数或者用algorithm中的__gcd( , )函数),求多个数的最大公因数可以先找出这些数中的最小的数,然后用for循环从那个最小的数遍历到0,若中途遍历到的一个数可以被所有那些数整除,那么此时遍历到的那个数就是那些数的最大公因数。下面是代码:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<int> vt;
	int n,a,min=99999999,flag=1,mi,ans=0;
	cin>>n;
	for(int i=1;i<=n;++i)
	{
		cin>>a;
		if(a<min) min=a;
		vt.push_back(a);
	}
	//cout<<min<<endl;
	for(int i=min;i>=0;--i)
	{
		//cout<<" "<<endl;
		//cout<<vt.size()<<endl;
		//cout<<flag<<endl;
		for(int j=0;j<vt.size();++j)
		{
			if(vt[j]%i!=0)
			{
				flag=0;
				break;
			}
		}
		if(flag)
		{
			mi=i;
			break;
		}
		flag=1;
	}
	cout<<mi<<endl;
	for(int i=0;i<vt.size();++i)
	{
		ans+=vt[i]/mi;
	}
	cout<<ans<<endl;
	return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值