素数筛法
素数筛法 :
建立一个标记数组 , 并将其初始化为 1 , 然后从元素 2 开始 , 每次让其 加上它本身 ,并且将其标记数组中的值记为 0 ,最后将标记数组中不为 0 的元素全部输出 。
int pt[1000] ; int main ( ) { for ( int i = 1 ; i <= 1000 ; i++ ) { pt[i] = 1 ; } pt[1] = 0 ; for ( int i = 2 ; i <= 1000 ; i++ ) { if ( pt[i] ) { for ( int j = 2*i ; j <= 1000 ; j += i ) { pt[j] = 0 ; } } } for ( int i = 1 ; i <= 1000 ; i++ ) { if ( pt[i] ) cout << i << '\t' ; } return 0 ; }
由此引申一道类似题目 :
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.
But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).
Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take?
Note: A Pokemon cannot fight with itself.
The input consists of two lines.
The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab.
The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
Print single integer — the maximum number of Pokemons Bash can take.
3
2 3 4
2
5
2 3 4 6 7
3
gcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.
In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.
In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
题目大意 :
输出一组最大公约数不为 1 , 并且长度最长的数组长度 。
AC代码 :
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> using namespace std ; #define Max(a,b) a>b?a:b #define Min(a,b) a>b?b:a #define ll long long int pre[100005] ; int main ( ) { int n , x ; while ( ~scanf ( "%d" , &n ) ) { memset ( pre , 0 , sizeof(pre) ) ; int t = 0 ; for ( int i = 0 ; i < n ; i++ ) { scanf ( "%d" , &x ) ; pre[x]++ ; t = Max ( t , x ) ; } int ans = 1 ; for ( int i = 2 ; i <= t ; i++ ) { int sum = 0 ; for ( int j = i ; j <= t ; j += i ) { sum += pre[j] ; } ans = Max ( sum , ans ) ; } printf ( "%d\n" , ans ) ; } return 0 ; }