【素数筛+合数分解】——hdu2710
Max Factor
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6386 Accepted Submission(s): 2094
Problem 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.
(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
* 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
Source
题意:找到n个数里具有最大素因子的数
(套用邝斌模板)
附上代码:
#include<stdio.h> #include<iostream> #include<algorithm> #include<string.h> using namespace std; const int MAXN=20000; int prime[MAXN+1]; long long factor[100][2];//[][0]位记录是因子的素数;[][1]记录可以被除几次 int facCnt;//不同素因子个数 //得到小于等于MAXN的素数,prime[0]存放的是素数的个数 void getPrime() { memset(prime,0,sizeof(prime)); for(int i=2;i<=MAXN;i++) { if(prime[i]==0) { prime[++prime[0]]=i;//往下一个空位放素数 } for(int j=1 ; j<=prime[0]/*找已经找到的素数*/ && prime[j]<=MAXN/i/*这个素数还要可以倍增*/ ; j++) { prime[prime[j]*i]=1;//标记找到的非素数 if(i%prime[j]==0)//如果i不是素数 { break; } } } } //把x进行素数分解 int getFactors(long long x) { facCnt=0;//初始化 long long tmp=x; for(int i=1 ; prime[i]<=tmp/prime[i]/*prime[i]^2<=tmp*/ ; i++) { factor[facCnt][1]=0; //找到是x的因子的素数 if(tmp%prime[i]==0) { factor[facCnt][0]=prime[i]; while(tmp%prime[i]==0)//一直往下除到底 { factor[facCnt][1]++; tmp/=prime[i]; } facCnt++; } } if(tmp!=1) { factor[facCnt][0]=tmp;//最后变成一个素数 factor[facCnt++][1]=1; } //factor[facCnt-1][0]里面存的是最大素因子 return facCnt;//返回给全局变量 } int main() { getPrime();//打表‘ int n; int num; while(scanf("%d",&n)!=EOF) { int ans=0;//结果 int temp=0;//记录目前最大的因子 for(int i=0;i<n;i++) { scanf("%d",&num); if(num==1)//1的时候要单独处理一下 { if(temp<1) { temp=1; ans=1; } continue; } getFactors(num); if(temp<factor[facCnt-1][0]) { temp=factor[facCnt-1][0]; ans=num; } } printf("%d\n",ans); } return 0; }

浙公网安备 33010602011771号