题目:
To improve the organization of his farm, Farmer John labels each of his N (1 <= N <= 5,000) cows with a distinct serial number in the range 1…20,000. Unfortunately, he is unaware that the cows interpret some serial numbers as better than others. In particular, a cow whose serial number has the highest prime factor enjoys the highest social standing among all the other cows.
为了改善农场的组织结构,农场主约翰给他的每头牛(1头≤N≤5,000头)都贴上了不同的序列号,序列号范围为1…两万。不幸的是,他没有意识到奶牛对一些序列号的解释比其他的更好。特别是,在所有的奶牛中,序列号具有最高质因数的奶牛享有最高的社会地位。
(Recall that a prime number is just a number that has no divisors except for 1 and itself. The number 7 is prime while the number 6, being divisible by 2 and 3, is not).
(回想一下,素数只是一个除了1和它本身以外没有除数的数。数字7是质数,而被2和3整除的数字6不是质数。
Given a set of N (1 <= N <= 5,000) serial numbers in the range 1…20,000, determine the one that has the largest prime factor.
给定一组范围为1的N(1≤N≤5,000)个序列号…20,000,确定最大质因数的那个。
Input
- Line 1: A single integer, N
- Lines 2…N+1: The serial numbers to be tested, one per line
第1行:单个整数,N
第2行…N+1:要测试的序列号,每行一个
Output
- Line 1: The integer with the largest prime factor. If there are more than one, output the one that appears earliest in the input file.
第1行:素数因子最大的整数。如果有多个,输出输入文件中最早出现的一个。
测试样例
//先制作最大素数因子表,再将输入的数与表的索引对应得到
//该数的最大素数因子,比较后即可得到结果
#include<iostream>
using namespace std;
int main(){
//max代表最大素数因子,max_i代表拥有最大素数因子的数
int i,n,j,k,k_i,max=0,max_i=0;
//制作最大素数因子表
int arr[20005];
for(i=0;i<20005;i++){ arr[i]=1; } //数组初始化为1
//求2-20004的最大素数因子
for(i=2;i<20005;i++){
//当因子i不是素数(即:已被小于i的因子赋值过了)时,会跳过该因子
if(arr[i]==1){
for(j=1;j*i<20005;j++){
arr[j*i]=i;
}
}
}
//找出拥有最大素数因子的数
while(cin>>n){
max=0;
max_i=0;
for(i=0;i<n;i++){
//输入数
cin>>k_i;
//k=该数的最大素数因子
k=arr[k_i];
//比较后,储存较大的素数因子,且因为题目要求在素数因子相同
//的情况下输出最早出现的数,所以判断时max>=k,而不是m>k
max_i = max>=k?max_i:k_i;
max = max>=k?max:k;
}
cout<<max_i<<endl;
}
return 0;
}