【问题标题】:c++ Multiples of 5 in sieve of atkin implemenationc ++ atkin实现筛中5的倍数
【发布时间】:2013-08-13 00:55:37
【问题描述】:

我正在解决项目 euler 的一个问题,该问题要求我找到 200 万以下的所有素数之和。我试图实现阿特金的筛子,奇怪的是它把像 65,85 这样的数字设置为素数。我看了一天多的代码和算法,但找不到任何问题。我确定它一定很愚蠢,但我找不到它。提前致谢 我正在使用 Visual Studio Express 2012。

代码如下:

#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <vector>
#include <fstream>
#include <conio.h>

 int main(){
    long long int limit,n;
    std::cout<<"Enter a number...."<<std::endl;
    std::cin>>limit;

    std::vector<bool> prime; 


    for(long long int k=0;k<limit;k++){ //sets all entries in the vector 'prime' to false
        prime.push_back(false);
    }

    long long int root_limit= ceil(sqrt(limit));

    //sive of atkin implementation
    for(long long int x=1;x<=root_limit;x++){

        for(long long int y=1;y<=root_limit;y++){

            n=(4*x*x)+(y*y);
            if(n<=limit && (n%12==1 || n%12==5)){
                prime[n]=true;
            }

            n=(3*x*x)+(y*y);
            if(n<=limit && n%12==7){
                prime[n]=true;
            }

            n=(3*x*x)-(y*y);
            if(x>y && n<=limit && n%12==11){
                prime[n]=true;
            }
        }
    }


    //loop to eliminate squares of the primes(making them square free)
    for(long long int i=5;i<=root_limit;i++){
        if(prime[i]==true){
            for(long long int j=i*i;j<limit;j+=(i*i)){
                prime[j]=false;
            }
        }
    }
    unsigned long long int sum=0;

    //print values to a seperate text file 
    std::ofstream outputfile("data.txt");
    outputfile<<"2"<<std::endl;
    outputfile<<"3"<<std::endl;
    for(long long int l=5;l<limit;l++){
        if(prime[l]==true){
            sum+=l;
            outputfile<<l<<std::endl;;
        }
    }

    outputfile.close();


    std::cout<<"The sum is...."<<sum+5<<std::endl;

    prime.clear();
    return 0;
}

和她的 data.txt 我指出了一些错误

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 65

【问题讨论】:

    标签: c++ sieve-of-atkin


    【解决方案1】:

    您应该将条目翻转到筛子列表中。在第一个嵌套 for 循环而不是 prime[n]=true; 中,您应该有 prime[n]=!prime[n];

    【讨论】:

    • 但我不明白这与将 value 设置为 true 有何不同......你能解释一下吗?谢谢:)
    • 某些值(例如 1985)被多次“访问”(即其中一个 if 成功)。第一次将 p[n] 设置为 true,第二次将其设置回 false。
    猜你喜欢
    • 2014-03-14
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多