本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。
本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!
Description
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.
(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).
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.
Input
* Line 1: A single integer, N
* Lines 2..N+1: The serial numbers to be tested, one per line
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.
Sample Input
4
36
38
40
42
Sample Output
38
Hint
OUTPUT DETAILS:
19 is a prime factor of 38. No other input number has a larger prime factor.
19 is a prime factor of 38. No other input number has a larger prime factor.
Source
正解:线性筛+暴力
解题报告:
直接筛出质数,然后暴力就可以了。
我连线性筛都写挂了一次,真是没救了...
//It is made by ljh2000
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <stack>
using namespace std;
typedef long long LL;
const int MAXN = ;
const int MAXM = ;
int n,N,a[MAXN],maxl[MAXN];
int cnt,prime[MAXM],ans;
bool vis[MAXM]; inline int getint(){
int w=,q=; char c=getchar(); while((c<''||c>'') && c!='-') c=getchar();
if(c=='-') q=,c=getchar(); while (c>=''&&c<='') w=w*+c-'',c=getchar(); return q?-w:w;
} inline void work(){
n=getint(); for(int i=;i<=n;i++) a[i]=getint(),N=max(a[i],N); ans=; int x;
for(int i=;i<=N;i++) { if(!vis[i]) prime[++cnt]=i; for(int j=;j<=cnt && i*prime[j]<=N;j++) { vis[i*prime[j]]=; if(i%prime[j]==) break;} }
for(int i=;i<=n;i++) {
x=a[i];
for(int j=;j<=cnt;j++) {
if(x%prime[j]!=) continue;
maxl[i]=prime[j]; while(x%prime[j]==) x/=prime[j];
if(x==) break;
}
}
for(int i=;i<=n;i++) if(maxl[i]>maxl[ans]) ans=i;
printf("%d",a[ans]);
} int main()
{
work();
return ;
}