Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- #include <vector>
- #include <fstream>
- using namespace std;
- vector<int> sequence(string path) {
- ifstream file(path);
- vector<int> seq;
- if (!file) cerr << "Error: file not exist!\n";
- else {
- string numbers = "";
- string line;
- while (getline(file, line)) numbers += line + " ";
- file.close();
- istringstream iss(numbers);
- int number;
- while (iss >> number) seq.push_back(number);
- }
- return seq;
- }
- // Проверка числа на простоту
- bool is_prime(int num) {
- bool prime;
- if (num == 2 || num == 3 || num == 5) prime = true;
- else if (~num & 1 || num < 2 || 0 == num % 3 || 0 == num % 5) prime = false;
- else {
- int n;
- for (n = 3; n * n <= num && num % n; n += 2) { ; }
- prime = n * n > num ? true : false;
- }
- return prime;
- }
- vector<int> sequence(vector<int>& numbers) {
- vector<int> primes;
- for (auto number : numbers) if (is_prime(number)) primes.push_back(number);
- return primes;
- }
- string format(vector<int>& numbers) {
- string line = "";
- for (auto number : numbers) line += to_string(number) + " ";
- return line;
- }
- void save(string& path, string& line) {
- ofstream file(path);
- if (!file) cerr << "Error: could not create file!\n";
- else {
- file << line;
- file.close();
- }
- }
- int main() {
- // Файл-источник всех чисел
- string source = "numbers.txt";
- // Файл для сохранения простых чисел
- string destination = "primes.txt";
- // Получаем коллекцию всех чисел из файла
- auto numbers = sequence(source);
- // Получаем коллекцию всех простых чисел
- auto primes = sequence(numbers);
- // Преобразуем коллекцию к строке
- auto line = format(primes);
- // Сохраним строку в файл
- save(destination, line);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement