程序不适用于大于1000的数字

时间:2013-09-13 18:23:05

标签: c++

我编写了这个简单的代码来实现Eratosthenes算法来计算素数并以某种有序的方式输入它们。问题是它不适用于大于1020的数字。有人能告诉我这个的原因吗?当我运行它时,Eclipse无法启动exe文件并停止计算数字。 但是,用Java编写的相同代码适用于不到10亿的数字。

#include <iostream>
#include<math.h>
using namespace std;


int main() {
    int N;
    cin >> N;
    int* a = new int[N];

    int i , j, k, cnt = 0;
        for(a[1] = 0, i = 2; i <= N; i++) a[i] = 1;
    for(i = 2; i <= N/2; i++)
        for(j = 2; j <= N/i; j++)
            a[i*j] = 0;


        for(i = 1; i <= N; i++)
            if(a[i]) {
                cout<< i ;
                int lengthi = (int)floor(log10((float)i));
                int lengthN = (int)floor(log10((float)N)) + 1;
                    for(k = 0; k < lengthN - lengthi + 1; k++)
                         cout<<' ';
                cnt++;
                if(cnt%10==0) cout<<'\n';
            }

    delete [] a;
    return 0;
}

1 个答案:

答案 0 :(得分:3)

您的格式是可怕的,但在将其转换为使用std::vector而不是手动管理循环后,它可以正常工作:

http://ideone.com/y2CML7

#include <cmath>
#include <iostream>
#include <vector>

int main() 
{
    int N = 1020;

    std::vector<int> a;
    a.resize(N);

    int i, j, k, cnt = 0;
    a[0] = 0;
    for(i = 1; i < N; i++) // fixed your indexing here
    {   
        a[i] = 1;
    }

    for(i = 2; i <= N/2; i++)
    {
        for(j = 2; j <= N/i; j++)
        {
            a[i*j] = 0; // I haven't done the math, but this may go out of bounds as well
        }
    }


    for(i = 1; i <= N; i++)
    {
        if(a[i]) 
        {
            std::cout << i;
            int lengthi = (int)std::floor(std::log10((float)i));
            int lengthN = (int)std::floor(std::log10((float)N)) + 1;
            for(k = 0; k < lengthN - lengthi + 1; k++)
            {
                std::cout << ' ';
            }
            cnt++;

            if(cnt%10==0)
            {
                std::cout << '\n';
            }
        }
    }

    return 0;
}

或算法的简化版本:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>


struct moduloFunctor
{
    int mod;

    moduloFunctor(int m) : mod(m) {}

    bool operator()(int i)
    {
        return (i % mod == 0 && i != mod);
    }
};


int main()
{
    std::vector<int> numbers;
    int maximum = 1020;
    //std::cin >> maximum;
    numbers.reserve(maximum - 1); // starting at 2
    for (int i = 2; i <= maximum; ++i)
    {
        numbers.push_back(i);
    }

    int cnt = 0;
    do
    {
        moduloFunctor func(numbers[cnt++]);
        numbers.erase(std::remove_if(numbers.begin(), numbers.end(), func), numbers.end()); 
    } while (cnt < numbers.size());

    std::cout << "Primes:  " << std::endl;
    std::copy(numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout, " "));

    return 0;
}