素数判断2710

原理很简单,就是当i是质()数的时候,i的所有的倍数必然是合数。如果i已经被判断不是质数了,那么再找到i后面的质数来把这个质

数的倍数筛掉。

    一个简单的筛素数的过程:n=30

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

     1 步过后2 4 ... 28 3015个单元被标成false,其余为true

     2 步开始:

     i=3;  由于prime[3]=true, prime[6], [9], [12], [15], [18], [21], [24], [27], [30]标为false.

     i=4;  由于prime[4]=false,不在继续筛法步骤。

     i=5;  由于prime[5]=true, prime[10],[15],[20],[25],[30]标为false.

     i=6>sqrt(30)算法结束。

     3 步把prime[]值为true的下标输出来:

     for(i=2; i<=30; i++)

     if(prime[i]) printf("%d ",i);

    结果是 2 3 5 7 11 13 17 19 23 29


Max Factor

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2511    Accepted Submission(s): 771


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.
 

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
 

Source
USACO 2005 October Bronze
 

Recommend
teddy

#include<iostream>
using namespace std;
#define kn 20005
int main()
{
int n,s1,max,ju,s[kn];
//freopen("in.txt","r",stdin);
for(int a=1;a<kn;a++)
s[a]=1;
for(int j=2;j<kn;j++)
{
if(s[j]==1)
for(int i=j*2;i<kn;i+=j)
s[i]=0;
}
while(cin>>n)
{
max=0;
while(n--)
{
cin>>s1;
for(int k=1;k<=s1;k++)
if(s[k]==1&&s1%k==0&&max<k)
{
ju=s1;max=k;
}
}
cout<<ju<<endl;
}
return 0;
}

你可能感兴趣的:(素数判断2710)