模板:线性筛质数

线性筛质数

功能

输出从 0 1000000 的所有质数。

思路

首先 0 1 不是质数,从 2 开始逐个判断是否为质数。如果 t 为质数,那么对于任意正整数 k k × t 不是质数,因此可以将 k × t 筛去。如果 t 已经被筛去,那么 t 不是质数,但仍然要将 k × t 筛去。为了避免重复筛选,需要对筛选条件加以限制,当且仅当 k k × t 除了 1 以外的最小因数时将 k × t 筛去,这样可以保证每个数最多被筛选 1 次。当 k × t 被筛去时, k 必然为质数,对于 t ,如果 t 为质数,那么 k 2 t ;如果 t 为合数,那么 k 2 t 除了 1 以外的最小因数。

时间复杂度

O ( n )

模板

#include <iostream>
using namespace std;
#include <cstring>

const int MAX = 1000000;

int pos;  // the amount of prime
int check[MAX];  // 0 to prime, 1 to composite
int prime[MAX];  // the prime numbers

/**
  * @other: 0 and 1 are not prime numbers
  */
void PRIME() {
  memset(check, 0, sizeof(check));
  pos = 0;
  for (int i = 2; i < MAX; ++i) {
    if (check[i] == 0) prime[pos++] = i;
    for (int j = 0; j < pos; ++j) {
      if (prime[j]*i > MAX) break;  // check the numbers in the range
      check[prime[j]*i] = 1;
      if (i % prime[j] == 0) break;  // to avoid checking repeatly
    }
  }
}

扩展1

利用筛选得到的质数对n进行分解质因数。

模板1.1

#include "PRIME.h"

int count[MAX];  // the amount of prime numbers

/**
  * @param n: number N
  */
void EXT1(int n) {
  memset(count, 0, sizeof(count));
  for (int i = 0; n > 1; ++i) {
    while (n % prime[i] == 0) ++count[i];
  }
}

模板1.2

#include "EXT1.h"

int amount;  // the amount of prime factors
int factor[MAX];  // the prime factors

/**
  * @param n: number N
  */
void EXT2(int n) {
  amount = 0;
  for (int i = 0; prime[i]*prime[i] <= n; ++i) {
    while (n % prime[i] == 0) {
      nums[amount++] = prime[i];
      n /= prime[i];
    }
  }
  if (n > 1) nums[amount++] = n;
}

扩展2

计算n所有因数的和。设一共有 k 种质因数,质因数 t i 的数量为 a i ,那么因数和为 i = 1 k j = 0 a i t i j

模板2

#include "EXT2.h"

/**
  * @param n: number N
  * @return: the sum of factors
  */
int EXT3(int n) {
  int ans = 1;  // the sum of factors
  for (int i = 0; i < pos; ++i) {
    int tmp = 1;  // the power of prime[i]
    int sum = 1;  // the sum of powers
    for (int j = 0; j < count[i]; ++j) {
      tmp *= prime[i];
      sum += tmp;
    }
    ans *= sum;
  }
  return ans;
}

猜你喜欢

转载自blog.csdn.net/Fast_G/article/details/80949569