[Cpp]
# Include <iostream>
# Include <cmath>
Using namespace std;
Const int nmax= 10000000;
Int isPrime [nMax];
Int prime [nMax];
Int factor [nMax];
Int len;
Void f1 () // simple Filter
{
Int n; // calculates the prime number between [1, n ].
Scanf ("% d", & n );
Len = 0;
Memset (isPrime, 0, sizeof (isPrime ));
IsPrime [0] = isPrime [1] = 1;
Int I;
For (I = 2; I <= n; ++ I)
{
If (! IsPrime [I])
{
Prime [len ++] = I;
IsPrime [I] = 1;
_ Int64 j;
For (j = (_ int64) I * I; j <= n; j + = I) // here I * I will cross the border
IsPrime [j] = 1;
}
}
}
Void f2 () // linear filtering. Modify the formula on f1. Use the minimum prime factor of the sum to search for the sum each time. The speed can be increased by 2 times, but I don't feel very good.
{
Int n; // calculates the prime number between [1, n ].
Scanf ("% d", & n );
Len = 0;
Memset (isPrime, 0, sizeof (isPrime ));
IsPrime [0] = isPrime [1] = 1;
Int I;
For (I = 2; I <= n; ++ I)
{
If (! IsPrime [I])
Prime [len ++] = I;
Int j;
For (j = 0; j <len & I * prime [j] <= n; ++ j)
// Each time I is updated, all prime numbers are traversed once. If I is a multiple of the prime numbers, it jumps out of the loop to avoid repeated operations.
{
IsPrime [I * prime [j] = 1;
If (I % prime [j] = 0)
Break;
}
}
}
Int max (int a, int B)
{
Return a> B? A: B;
}
Void f3 () // calculate the prime number in the interval. Two points are obtained. The first is to multiply the two numbers to obtain all the total numbers. Second, use a mobile array to mark
{
Int a, B; // calculates all prime numbers between the intervals [a, B ].
Scanf ("% d", & a, & B );
If (a = 1) a ++; // Special Judgment is required for 1, because it is never marked
Int m = sqrt (B + 0.5 );
Int I;
For (I = 2; I <= m; ++ I)
{
Int j;
For (j = max (I, a/I); j <= B/I; ++ j)
If (I * j-a> = 0)
IsPrime [I * j-a] = 1;
}
Len = 0;
For (I = a; I <= B; ++ I)
If (! IsPrime [I-a])
Prime [len ++] = I;
}
Void f4 () // minimum prime factor. The function is similar to f2 ().
{
Int n; // calculate the prime factor of all numbers in [1, n ].
Scanf ("% d", & n );
Memset (isPrime, 0, sizeof (isPrime ));
Len = 0;
Int I;
Factor [1] = 1;
For (I = 2; I <= n; ++ I)
{
If (! IsPrime [I])
{
Prime [len ++] = I;
Factor [I] = I;
}
Int j;
For (j = 0; j <len & I * prime [j] <= n; ++ j)
{
IsPrime [I * prime [j] = 1;
Factor [I * prime [j] = prime [j];
If (I % prime [j] = 0)
Break;
}
}
For (I = 1; I <= n; ++ I)
{
Printf ("I = % d, factor = % d \ n", I, factor [I]);
}
}
Void print ()
{
Int I;
For (I = 0; I <len; ++ I)
{
Printf ("% d \ t", prime [I]);
If (I + 1) % 5 = 0)
Printf ("\ n ");
}
Printf ("\ n ");
}
Int main ()
{
/*
F1 ();
Print ();
F2 ();
Print ();
F3 ();
Print ();*/
F4 ();
Return 0;
}
Author: lhshaoren