I am writing a program that creates two vectors to practice comparing elements in a vector. The first vector is a list of all numbers that are not prime numbers between 1-100 (not prime numbers), the second vector is a list of all numbers between 1-100 (vector number_bank). I am using loops to compare each element in the vectors. Lets say the number 5 comes up from the number_bank (which is a prime number), if this number does not match any number in the not_prime_numbers vector then it is pushed back into a third vector called prime numbers. If a number like 4 were to be compared to the elements of the not_prime_number list it is supposed to match with the number 4 in this list and break the loop without pushing back the number into the prime_numbers vector. What is happening is all numbers between 1-100 are being pushed back. 4 in the number_bank vector is never equal to the 4 in the not_prime_numbers vector so the cycle continues pushing back 4 into the prime numbers vector.
There is no math involved changing the elements in these vectors so there shouldn't be an incremental margin of error (epsilon) usually associated with comparing floats. Is there a better way to compare the elements in these vectors?
int main()
{
float i = 1.0;
unsigned int n = 0;
std::vector<float>not_prime_numbers;
std::vector<float>number_bank;
std::vector<float>prime_numbers;
while (i < 101.0)
{
for (float j = 1.0;j<(i);++j)
{
float p = i / j;
if (abs(floor(p)) == p&&j!=1.0)
{
not_prime_numbers.push_back(i);
break;
}
}
++i;
}
for (float k = 1.0; k < 101.0; ++k)
{
number_bank.push_back(k);
}
for (unsigned int m = 0; m < number_bank.size(); ++m)
{
while (n < not_prime_numbers.size())
{
if (not_prime_numbers[n] == number_bank[m]) // here is where i try to break the loop
{
break;
}
if (n == (not_prime_numbers.size()-1))
{ // here is where element is pushed back when compared to all loop elements
prime_numbers.push_back(number_bank[m]);
break;
}
if (not_prime_numbers[n] != number_bank[m])
{
++n;
}
}
}
std::cout << "All prime numbers between 0 and 100 are as follows:\n";
for (unsigned int j = 0; j < prime_numbers.size(); ++j)
{
std::cout << prime_numbers[j] << "\n";
}
return 0;
}
I read about .compare and tried it but it states that there needs to be a class structure to the left (perhaps a vector has no class structure?). I'm new to C++ and would greatly appreciate the help.