2

I'm doing question 4.11 in Bjarne Stroustrup Programming-Principles and Practice Using C++. Create a program to find all prime numbers in the range from 1 to max using a vector of primes in order(prime[2,3,5,...]). Here is my solution:

#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
bool check_prime(vector<int> &prime, int n) {
  int count = 0;
  for (int i = 0; prime[i] <= n || i <= prime.size() - 1; ++i) {
    if (n % prime[i] == 0) {
      count++;
      break;
    }
  }
  bool result = 0;
  if (count == 0)
    result = 1;
  else
    result = 0;
  return result;
}

int main() {
  vector<int> prime{2};
  int max;
  cout << "Please enter a max value:";
  cin >> max;
  for (int i = 2; i <= max; ++i) {
    if (check_prime(prime, i))
      prime.push_back(i);
  }
  for (int i = 0; i <= prime.size() - 1; ++i) {
    cout << prime[i];
    if (i <= prime.size() - 2)
      cout << ',';
  }
}

My code is working for numbers smaller than 23 but fail to work for anything bigger. If I open the program in Windows 10 the largest working number increase to 47, anything bigger than that fail to work.

Manthan Tilva
  • 3,135
  • 2
  • 17
  • 41
Cuong
  • 23
  • 3

2 Answers2

1

You check prime[i]<=n before i<=prime.size()-1. Then, if it's true (even if i>prime.size()-1, which is random behaviour), you work on it, generating wrong results.

Caduchon
  • 4,574
  • 4
  • 26
  • 67
1

This condition

prime[i]<=n||i<=prime.size()-1

makes the loop continue as long as at least one of them is true, and you're accessing prime[i] without checking the value of i.
This will cause undefined behaviour as soon as i == prime.size().
This means that anything can happen, and that you're experiencing that any specific values are working is just an unfortunate coincidence.

You need to check the boundary first, and you should only continue for as long as both conditions are true:

i <= prime.size() - 1 && prime[i] <= n 

which is more idiomatically written

i < prime.size() && prime[i] <= n 

(It's never too soon to get comfortable with the conventional half-open intervals.)

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Thanks. I look at it for half an hour and didnt notice that I use || instead of &&. And somehow it works for small max number which confused me greatly. – Cuong Nov 20 '19 at 13:48