Eratosthenes的筛子和哥德巴赫猜想

时间:2017-03-19 18:46:10

标签: c++ sieve

Eratosthenes的筛子和哥德巴赫的猜想

实施Eratosthenes筛选并使用它来查找所有素数 数字小于或等于一百万。使用结果 证明了哥德巴赫猜想所有甚至四和四的整数 一百万,包括在内。

使用以下声明实现一个函数:

void sieve(int array [],int num); 此函数将整数数组作为其参数。阵列 应该初始化为1到1000000的值 函数修改数组,以便只保留素数; 所有其他值都归零。 必须编写此函数以接受任何整数数组 尺寸。您必须输出1到1之间的所有素数 1000000,但是当我测试你的函数时,它可能在一个数组上 不同的大小。

使用以下声明实现一个函数:

void goldbach(int array [],int num); 此函数采用与上一个函数相同的参数 并显示4到1000000之间的每个偶数整数和两个 添加到它的素数。 这里的目标是提供有效的实施。这个 在确定是否时,表示没有乘法,除法或模数 一个数字是素数。这也意味着第二个功能必须找到 两个素数有效。

程序的输出:1到1000000之间的所有素数 以及4到1000000之间的所有偶数和两个素数 总结它的数字。

请勿为此项目提供输出或会话记录!

这是我到目前为止的代码,我的问题是它显示的数字高于1,000为1,我该怎么办呢,谢谢!

#include <iostream>
#include <stdio.h>
#include <math.h>

using namespace std;

void sieve(int array[], int num);
void goldbach(int array[], int num);

const int arraySize = 1000000;
int nums[arraySize];

int main(){

    for (int i = 0; i <= arraySize; ++i)
        nums[i] = 1;

    nums[0] = nums[1] = 0;

    sieve(nums, arraySize);

    for(int i = 0; i < 10000; ++i){
        if (nums[i] > 0){
            cout << nums[i] << " "; 
        }
    }

    goldbach(nums, arraySize);

    return 0;
}


void sieve(int array[], int num) {

    int squareR = (int)sqrt(num);

    for(int i = 2; i <= squareR; ++i){

        int k;
        if(array[i]){
            for(k = i*i; k <= num; k += i)
                array[k] = 0;
        }

        if (array[i] == 1){
            array[i] = i;   
        }     
    }
}


void goldbach(int array[], int num){

    int i, r = 0;
    for (i = 4; i <= num; i += 2){

        for (int j = 2; j <= i/2; j++)

            if (array[j] && array[i-j]) r ++;
    }
}

1 个答案:

答案 0 :(得分:0)

  

我的问题是它显示的数字高于1,000作为1,我该怎么做呢

那是因为您没有更新1000以上数组中的值,此处:

for(int i = 2; i <= squareR; ++i){
   ...
    if (array[i] == 1){
        array[i] = i;

显然,squareR上方的数组条目不会更新,并保持在您初始化它们的值,即1

但是,我根本不需要此更新。您可以删除它并简化代码,将数组的条目保持为1(对于素数)或0(对于非素数)。使用此功能,并显示您的结果(在main中):

for(int i = 0; i < arraySize; ++i){
    if (nums[i] != 0){
        // cout << nums[i] << " "; // <-- drop this
        cout << i << " ";          // <-- use this
    }
}
相关问题