为什么这个循环在第一次迭代时会中断?

时间:2014-11-08 18:03:44

标签: c++ algorithm vector

我正在学习C ++并试图创建一个从1到100迭代的程序并发现所有素数,但基本上它在乘法函数的第一次迭代中停止。

cout << "Base: " << base << " To: " << to << " Check: " << check << " tmp: " << tmp << endl;

我已将其添加以检查停止位置

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

using namespace std;

int multiply(int base, int to, int check, vector<int> &all_numbers) {

    int tmp;

    for(int i = 1; i <= to; i++) {

        tmp = base * i;

        if(tmp != check) {

            cout << "Base: " << base << " To: " << to << " Check: " << check << " tmp: " << tmp << endl;

            if( (tmp % check) == 0 ) {

                if( find( all_numbers.begin(), all_numbers.end(), tmp ) != all_numbers.end() ) {

                    all_numbers.erase( remove( all_numbers.begin(), all_numbers.end(), tmp ), all_numbers.end() );

                }

            }

        }

    }

    return 0;

}

int main(int argc, char** argv) {

    int top = 100;
    vector<int> primes;

    for(int i = 1; i <= top; i++) {

        primes.push_back(i);

    }

    for(int i = 0; i < top; i++) {

        multiply(1, top, i, primes);

    }

    for(vector<int>::iterator it = primes.begin(); it != primes.end(); ++it) {

        cout << *it << " - ";

    }

    cout << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

Why does this loop break at the first iteration?

你在零中除以:

if( (tmp % check) == 0)

考虑这种方式:

bool isPrime(int n) {  
   if (n == 1 || n == 2)
      return false;   

   for (int i=2; i <= n/2; i++)
        if((n % i) == 0)
            return false;

   return true;
}

int main(int argc, char** argv) {
    int top = 100;
    vector<int> primes;

    for(int i = 1; i < top; i++)
        if (isPrime(i))
             primes.push_back(i);

    for(vector<int>::iterator it = primes.begin(); it != primes.end(); ++it)
        cout << *it << " - ";

    cout << endl;
    return 0;
}

输出:

3 - 5 - 7 - 11 - 13 - 17 - 19 - 23 - 29 - 31 - 37 - 41 - 43 - 47 - 53 - 59 - 61 - 67 - 71 - 73 - 79 - 83 - 89 - 97 -