Advertisement
NickAndNick

Простые числа. Чтение/запись файла

Apr 28th, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <fstream>
  5. using namespace std;
  6. vector<int> sequence(string path) {
  7.     ifstream file(path);
  8.     vector<int> seq;
  9.     if (!file) cerr << "Error: file not exist!\n";
  10.     else {
  11.         string numbers = "";
  12.         string line;
  13.         while (getline(file, line)) numbers += line + " ";
  14.         file.close();
  15.         istringstream iss(numbers);
  16.         int number;
  17.         while (iss >> number) seq.push_back(number);
  18.     }
  19.     return seq;
  20. }
  21. // Проверка числа на простоту
  22. bool is_prime(int num) {
  23.     bool prime;
  24.     if (num == 2 || num == 3 || num == 5) prime = true;
  25.     else if (~num & 1 || num < 2 || 0 == num % 3 || 0 == num % 5) prime = false;
  26.     else {
  27.         int n;
  28.         for (n = 3; n * n <= num && num % n; n += 2) { ; }
  29.         prime = n * n > num ? true : false;
  30.     }
  31.     return prime;
  32. }
  33. vector<int> sequence(vector<int>& numbers) {
  34.     vector<int> primes;
  35.     for (auto number : numbers) if (is_prime(number)) primes.push_back(number);
  36.     return primes;
  37. }
  38. string format(vector<int>& numbers) {
  39.     string line = "";
  40.     for (auto number : numbers) line += to_string(number) + " ";
  41.     return line;
  42. }
  43. void save(string& path, string& line) {
  44.     ofstream file(path);
  45.     if (!file) cerr << "Error: could not create file!\n";
  46.     else {
  47.         file << line;
  48.         file.close();
  49.     }
  50. }
  51. int main() {
  52.     // Файл-источник всех чисел
  53.     string source = "numbers.txt";
  54.     // Файл для сохранения простых чисел
  55.     string destination = "primes.txt";
  56.     // Получаем коллекцию всех чисел из файла
  57.     auto numbers = sequence(source);
  58.     // Получаем коллекцию всех простых чисел
  59.     auto primes = sequence(numbers);
  60.     // Преобразуем коллекцию к строке
  61.     auto line = format(primes);
  62.     // Сохраним строку в файл
  63.     save(destination, line);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement