您的位置:首页 > 其它

Gym 101028E-Teams-求一组数的最大公约数

2016-07-13 10:58 316 查看
题目描述:

ACM-SCPC-2017 is approaching every university is trying to do its best in order to be the Champion, there are
n universities, the
ith of them has exactly
ai contestants. No one knows what is the official number of contestants in each team yet, this year organizers are planing to minimize number of teams participating in the contest but they still want every
contestant to participate, so they should select a number
k so that each team will consist of exactly
k contestant from the same university. Every contestant will belong to one team exactly, and number of these teams is as minimum as possible. Your job is to help the organizers in their task by writing a program that calculates two integers
k, the number of contestants in each team, and
m, the minimum number of teams will participate.
1 ≤ n ≤ 1000, 1 ≤ ai ≤ 106

Input

First line of input contains an integer T denotes number of test cases. Each test case contains two lines: the first line contains one integer
n denotes number of universities, while the second line contains
n space-separated integers the
ith of them denotes number of contestants from the
ith university.

Output

For each test case, print one line containing two integers: the first one is
k, the size of each team, and the second one is
m, the minimum number of teams from all universities according to the previous conditions.

Sample Input

Input
2
3
5 15 10
4
4 6 8 12


Output
5 6
2 15

代码实现:

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int f(int a,int b)
{
int t;
while(b!=0)
{
t=a;
a=b;
b=t%b;
}
return a;
}
int main()
{
int t,n,i,a[1010],num,b;
cin>>t;
while(t--)
{
cin>>n;
num=0;
for(i=0;i<n;i++)
{
cin>>a[i];
}
b=a[0];
for(i=1;i<n;i++)
{
b=f(b,a[i]);
}
for(i=0;i<n;i++)
{
num+=(a[i]/b);
}
cout<<b<<" "<<num<<endl;
}
return 0;
}

1.求两个数的最大公约数用辗转相除法是很省时间的,辗转相除法的原理:gcd(a,b)=gcd(b,a%b)

2.刚开始超时是因为没有想到用辗转相除法,

1)从1开始到最大的数,对每一个数进行判断是否可以取余

2)两两开始求最大公约数

3)用了辗转相除法,但是错误,原因是我是先求a[0],a[1]的gcd=b,然后从2-n开始遍历,再求b=gcd(b,a[i])

如果总共有1个数,就不存在a[1],这就是错误原因

总结最近做的题,我感觉薄弱之处在于不怎么考虑数据范围
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: