筛素数法

#ifndef _PRIME_NUMBER_H_
#define _PRIME_NUMBER_H_


#include "string.h"
#include <iostream>

//筛素数法
int PrimeNumber(int n){
    if (n < 2){
        return -1;
    }

    bool *flag = new bool[n];
    memset(flag, false, n*sizeof(bool));

    int *prime = new int[n/3];

    int i, j;
    int pi = 0;
    for (i = 2; i < n;i++)
    {
        if (false==flag[i])
        {
            prime[pi++] = i;
            /*for (j = i; j < n; j += i) { flag[j] = true; }*/
        }   
        for (j = 0; j < pi && (i*prime[j] < n); j++)
        {
            flag[i*prime[j]] = true;

            if (i%prime[j] == 0){
                break;
            }
        }
    }

    for (int k = 0; k < pi; k++){
        std::cout << prime[k] << std::endl;
    }

    delete[] flag;
    delete[] prime;
    flag = nullptr;
    prime = nullptr;

    return 0;
}

你可能感兴趣的:(筛素数法)