# [POJ 3048] Max Factor【欧拉筛】

• 2017-12-30
• 0
• 0

## Problem:

 Time Limit: 1000MS Memory Limit: 65536K

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.

Source

USACO 2005 October Bronze

## Code: O(TNP), P为素数个数 [200K, 47MS]

```#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;

const int UPRANGE = 20000;
int prm[UPRANGE >> 1], prmSize;
bool isprm[UPRANGE + 2];

inline void initPrime(){
memset(isprm, 1, sizeof(isprm));
isprm = isprm = 0, prmSize = 0;
for(register int i = 2; i <= UPRANGE; i++){
if(isprm[i]) prm[++prmSize] = i;
for(register int j = 1; j <= prmSize && i * prm[j] <= UPRANGE; j++){
isprm[i * prm[j]] = 0;
if(i % prm[j] == 0) break;
}
}
}

int N, curid;
int ans, mxfac;

int main(){
initPrime();
while(scanf("%d", &N) != EOF){  // Notice that input contains several test cases
mxfac = 0;
while(N--){
scanf("%d", &curid);
int tmp = curid, curfac;
for(register int i = 1; i <= prmSize && prm[i] <= tmp; i++)
while(tmp % prm[i] == 0) tmp /= prm[i], curfac = prm[i];
if(curfac > mxfac) mxfac = curfac, ans = curid;
}
printf("%d\n", ans);
}
return 0;
}
```

#### 评论

49750

https://github.com/Darkleafin

OPEN AT 2017.12.10

Please refresh the page if the code cannot be displayed normally.

https://visualgo.net/en

- Theme by Qzhai