最小质因子

最小质因子

欧拉线性筛打表实现

原理:欧拉线性筛素数法,每个数仅使用其最小素因数筛去。

#include 
 
using namespace std;
 
inline int mini(int a, int b) {return a < b ? a : b;}
 
// 使用欧拉线性筛打最小质因子表
const int LIM = 1e6 + 10;       /* The limit of number to be test */
int prime[LIM / 3];
int miniFactor[LIM];
int primepos;
void euler() {
    int tmp;
    for (int i = 2; i < LIM; i++) {
        if (!miniFactor[i]) prime[primepos++] = i, miniFactor[i] = i;
        for (int j = 0; (tmp = i * prime[j]) < LIM; j++) {
            miniFactor[tmp] = prime[j];
            if (!(i % prime[j])) break;
        }
    }
}
 
// test program
int main(void) {
    euler();
    for (int i = 1; i <= 10; i++) {
        printf("the mini factor of %d is %d\n", i, miniFactor[i]);
    }
    printf("the mini factor of 47 is %d\n", miniFactor[47]);
    printf("the mini factor of 61 is %d\n", miniFactor[61]);
    printf("the mini factor of 561 is %d\n", miniFactor[561]);
 
    return 0;
}

 

你可能感兴趣的:(数学----数论)