HDU-2710 Max Factor

http://acm.hdu.edu.cn/showproblem.php?pid=2710

给定N个数,求出其中含有最大素因子的数。

两个代码:自己的恶心代码

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

int p[20010], max[20005];

inline int cal( int x )
{
	for( int i = x / 2; i >= 1; --i )
	{
	    if( !p[x] )
	        return x;
		if( !p[i] &&  x % i == 0 )
			return i;
	}
}

inline void getint( int &x )
{
    char c;
    while( c = getchar(), c < '0' || c > '9' ) ;
    x = c -'0';
    while( c = getchar(), c >= '0' && c <= '9' )
        x = x * 10 + c - '0';
    return;
}

int main()
{
	int N;
	for( int i = 4; i <= 20005; i += 2 )
	{
		p[i] = 1;
	}
	for( int i = 3; i <= 20005; ++i )
	{
		if( !p[i] )
		{
			int k = 2 * i;
			for( int j = i * i; j <= 20005; j += k )
				p[j] = 1;
		}
			
	}
	for( int i = 1; i <= 20000; ++i ) // 这个过程复杂化了
	{
		max[i] = cal( i );
	}
	while( scanf( "%d", &N ) == 1 )
	{
		int Max = -1, num, ans;
		for( int i = 0; i < N; ++i )
		{
			getint( num );
			if( Max < max[num] )
			{
				ans = num, Max = max[num];
			}
		}
		printf( "%d\n", ans );
	}
	return 0;
}

  新思路的代码:

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

int data[20005];

int main()
{
    int N;
    for( int i = 2; i <= 20000; ++i )
    {
        if( !data[i] )
        {
            for( int j = 1; i * j <= 20000; ++j )
                data[i*j] = i;
        }
    }
    while( scanf( "%d", &N ) == 1 )
    {
        int max = -1, ans;
        for( int i = 0; i < N; ++i )
        {
            int c;
            scanf( "%d", &c );
            if( max < data[c] )
            {
                ans = c;
                max = data[c];
            }
        }
        printf( "%d\n", ans );
    }

    return 0;
}

  

  

posted @ 2011-11-02 20:39  沐阳  阅读(343)  评论(0编辑  收藏  举报