Cod sursa(job #1551851)

Utilizator bolovMihail Balan bolov Data 16 decembrie 2015 19:24:50
Problema Fractii Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.23 kb
// http://www.infoarena.ro/problema/fractii

#include <fstream>
#include <vector>

class BitMatrix {
  std::vector<bool> buffer_;
  int num_cols_;

public:

  BitMatrix(int num_lines, int num_cols, bool value)
      : buffer_(num_lines * num_cols, value), num_cols_(num_cols) {}

  decltype(auto) at(int i, int j)  {
    return buffer_[i * num_cols_ + j];
  }
};

static auto get_num_fractions(int n) -> int {
  // fractions.at(i, j) == true <=> i/j and j/i irreductible
  // fractions.at(i, j) == true <=> i/j and j/i reductible
  BitMatrix fractions(n + 1, n + 1, true);

  for (auto k = 2; k <= n; ++k) {

    if (fractions.at(k, k) == false) {
      // k is not prime, was set previously, so nothing to do
      continue;
    }

    for (auto i = k; i <= n; i += k) {
      for (auto j = i; j <= n; j += k) {
        fractions.at(i, j) = false;
      }
    }
  }

  // for fractions with 1;
  auto sum = 2 * n - 1;

  for (auto i = 2; i <= n; ++i) {
    for (auto j = i; j <= n; ++j) {
      if (fractions.at(i, j) == true)
        sum += 2;
    }
  }
  return sum;
}

auto main() -> int {
  std::ifstream fin{"fractii.in"};
  auto n = int{};
  fin >> n;
  fin.close();

  std::ofstream fout{"fractii.out"};
  fout << get_num_fractions(n);

  return 0;
}