Find prime numbers between a given pair of numbers and store them into an array?

closed account (yCoiNwbp)
Find all the prime numbers between a given pair of numbers.
Numbers should be read in from an input file called "numbers.txt" and find all the prime numbers between them. Store the prime numbers in an array, then sort the array from greatest
to least. Display the array before and after the sort.

I'm stuck on how to put the prime numbers into an array.

The input file has the numbers 1 & 100.

Here's what I have so far.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream fin;
fin.open("numbers.txt");

int num1,
num2;

fin >> num1 >> num2;

for (int i = num1; i <= num2; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j))
{
break;
}
if (j==i)
{
cout << i << " ";
}
}
}

fin.close();
return 0;
}
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
#include <iostream> // std::cout
#include <fstream> //std::ifstream
#include <vector> // std::vector
#include <string> // std::string and USES C++11 std::stoi
#include <set> //std::set - removes the duplicates and sort
#include <utility> // std::pair and std::make_pair
std::pair< bool, unsigned> prime_number(unsigned number)
{
    bool ret = true;
    for(unsigned i = 2; i < number; i++)
        if ((number % i) == 0 && number != i) //The second piece is is the especial case 2
        { ret = false; break;}
    return std::make_pair(ret, number);
}

//Ok, lets start!
int main()
{
    std::ifstream file;
    std::string content;
    std::vector<unsigned> numbers;
    std::vector<unsigned> prime_numbers;
    file.open("numbers.txt");
    while(std::getline(file, content, ' ')) //I suppose the numbers separator is space ' '. We'll get the numbers
    {
        if(!content.empty())
        {
            if(std::stoi(content) < 0) numbers.push_back(std::stoi(content) * -1); //Turn negative numbers in positive.
            else numbers.push_back(std::stoi(content));
        }
    }
    for(auto a : numbers)
    {
        std::pair < bool, unsigned > b (prime_number(a));
        if(b.first) prime_numbers.push_back(b.second); //If is prime, push the number
    }
    if(prime_numbers.size())
    {
        std::set<unsigned> primes (prime_numbers.begin(), prime_numbers.end());
        std::cout << "Found " << prime_numbers.size() << " prime numbers in file \"numbers.txt\":\n";
        for(auto a : primes)
        {
            std::cout << a << "\t";
        }
    }
    else std::cout << "None prime numbers in file \"numbers.txt\".";
}
Topic archived. No new replies allowed.