### Finding Prime Numbers -Help Needed-

Hey guys, I'm trying to write a program that loops through numbers 1 to 100 and adds all the prime numbers to a vector list of doubles. The problem Im having is that it gets some prime numbers right but doesn't always add the proper ones. When I output the vector list at the end of the program I get a bunch of numbers that shouldn't be there

[b][OUTPUT][\b]
3
5
7
9
11
13
15
17
19

Heres the code for the program, what Im doing here is testing all values that are divided by 2 (a prime number) to see if they leave any remainder. Im not sure Im understanding this correctly but I though this would work. Thanks guys.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546`` `````` // Bradley Latreille // Chapter 4 Exercise 11 // /* Fine all prime numbers between 1 and 100. */ #include "std_lib_facilities.h" vector prime_numbers; // create a vector to store our prime_numbers bool is_prime(int val) { if(val%2 == 0) { return false; }else{ return true; } } int main() try { // Loop through numbers 1 to 100 for(int i = 1; i < 100; i++) { // check if the number is prime if(is_prime(i)) { //cout << i << " is a prime number! Adding to primes list!\n"; prime_numbers.push_back(i); // add the number to our prime_numbers vector }else{ //cout << i << " is not a prime number! Skipping number!\n"; } } for(int i = 1; i < 100; i++) { cout << prime_numbers[i] << endl; } } catch (runtime_error e) { // this code is to produce error messages; it will be described in Chapter 5 cout << e.what() << '\n'; keep_window_open("~"); // For some Windows(tm) setups } catch (...) { // this code is to produce error messages; it will be described in Chapter 5 cout << "exiting\n"; keep_window_open("~"); // For some Windows(tm) setups }``````

 what Im doing here is testing all values that are divided by 2 (a prime number)

That's not what a prime number is. A prime number is a number exactly divisible by itself and one. You seem to be testing for odd numbers.
Last edited on
Okay sounds good :) It actually turned out the exercise was much simpler. He wanted me to test a loop of numbers 1 - 100 against a vector of already prime numbers, and store the found primes in a new vector. In later exercises he asks to do it without a vector of primes offers the "Sieve of Eratosthenes" approach to solving the problem :) Thanks for your help though!
Topic archived. No new replies allowed.