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.
#include <iostream>
#include <vector>
usingnamespace 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;
}
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";
}