Vector Run Time Error

Hi guys

I'm trying to help out a friend who's studying math. They have to develop a program, where you type in a number "n" and a number "k". Then you have to calculate how many numbers (which are between 2 and n) can be divided evenly by k prime numbers.

Here's what I got so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>

using namespace std;



int main ()
{
    // Variablen
    int n;
    int k;
    bool isPrime = false;
    vector<int> prime_numbers;

    // Abfragen
    cout << "Enter n: ";
    cin >> n;
    cout << "\n";

    cout << "Enter k: ";
    cin >> k;
    cout << "\n";



    // Rechnen
    for (int i = 2; i < n ; i++) //alle Zahlen von 2 bis n
    {
        isPrime = true;
        for (int j = 2; j < i; j++) //alle Zahlen durch alle Zahlen teilen
        {
            if (i%j == 0) //ist der Rest 0, ist die Zahl keine Primzahl
            {
                isPrime = false; //Primzahl-bool auf falsch setzen

            }
        }
        if (isPrime == true)
        {
            prime_numbers.push_back(i); //complete the list of prime numbers
            std::cout << i << ", ";
        }
    }

    std::cout << "\n" << "Prime number list for numbers smaller than " << n << " complete now...\n";//The list with prime numbers from 2 to n is now complete. We'll use this list to check how many numbers

    int composite_counter = 0;
    int temp = 0;

    for (int g = 2; g < n; g++)
    {
        for (int h = 0; h <= prime_numbers.size(); h++) //loop through the list of prime numbers
        {
            if (g % prime_numbers[h] == 0) //if the checked number divides evenly with a number from the list add one to counter
            {
                composite_counter++;
                temp = g;
                std::cout << "composite_counter: " << composite_counter << "\n";
                std::cout << "g: " << g << "\n";
            }
        }

        if (composite_counter == k)
        {
            cout << temp << "is a " << k << "-composite number.\n";
        }
        temp = 0;
        composite_counter = 0;
    }






    return 0;
}
Last edited on
The run time doesnt appear when I comment this part out:

1
2
3
4
5
6
7
if (g % prime_numbers[h] == 0) //if the checked number divides evenly with a number from the list add one to counter
            {
                composite_counter++;
                temp = g;
                std::cout << "composite_counter: " << composite_counter << "\n";
                std::cout << "g: " << g << "\n";
            }
Valid indices of an array of size n are 0 through n-1. Likewise, with a vector whose size method returns n, valid indices are 0 through n-1.
Topic archived. No new replies allowed.