I'm learning C++ and am trying to create a program that iterates from 1 to 100 and discovers all the prime numbers, but basically it stops at the fist iteration in the multiply function.
the
cout << "Base: " << base << " To: " << to << " Check: " << check << " tmp: " << tmp << endl;
i've added it to check where it stopped
#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;
}
Why does this loop break at the first iteration?
You are dividing by zero in:
if( (tmp % check) == 0)
Consider this way:
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;
}
Output:
3 - 5 - 7 - 11 - 13 - 17 - 19 - 23 - 29 - 31 - 37 - 41 - 43 - 47 - 53 - 59 - 61 - 67 - 71 - 73 - 79 - 83 - 89 - 97 -
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다