HDU 2710/POJ 3048 Max Factor

Max Factor

题目

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

Output

38

Hint

OUTPUT DETAILS:
19 is a prime factor of 38. No other input number has a larger prime factor.

解题思路

  对于这道题,我一开始的思路是是先用一个数组以0和1把所有的质数给标记出来,然后再从这组素数中求出所要求的数的最大质因子,但是效率要慢一下,我就想到可以直接用一个数组,该数组里存放的就是下标的最大质因子,效率会更快些。

  整体的流程就是,先把数组prime初始化为0,要注意的是这道题需要把1认为是质数,所以1要单独判断。然后i下标从2开始,先判断prime[i]是否为0,也就是判断是否存有质因子,如果不等于0那就是该下标已存有质因子则进入下一次循环,如果等于0,则先把i赋值给prime[i],再把i赋值给下标是i的倍数的prime数组,这样循环下来pirme[i]的值就是i的最大质因子。最后再按照题目要求输出即可。

  也就是,比如说在IsPrime()函数里第一次循环由于pirme[2] = 0,那么pirme[2] = 2,然后prime[4] = 2,prime[6] = 2等后边下标是2的倍数的都赋值2。第二次循环由于prime[3] = 0,那么prime[3] = 3,prime[6] = 3等后边下标是3的倍数都赋值3……这样循环到结束,prime[N]里存放的就是下标的最大质因子。

AC

#include <iostream>
#include <cmath>
const int N = 200001;
using namespace std;
int prime[N];		//用于存放下标i的最大质因子
void IsPrime()
{
    
    
    memset(prime,0,N);		//初始化prime数组为0
    prime[1] = 1;					//1要特殊处理
    for(int i = 2;i < N; i ++)
    {
    
    
        if(!prime[i])		//判断是否已存有质因子,0表示没有,
        {
    
    
            prime[i] = i;
            for(int j = i * 2; j < N; j += i)
                prime[j] = i;			
        }

    }
}
int main()
{
    
    
    IsPrime();
    int n,max = 0,result;
    cin>>n;
    for(int i = 0; i < n; i ++)
    {
    
    
        int t;
        cin>>t;
        if(prime[t]>max)
        {
    
    
            max = prime[t];
            result = t;
        }
    }
    cout<<result<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44786971/article/details/127360872