Cod sursa(job #2978619)

Utilizator BujorelActimelBujor Mihai Alexandru BujorelActimel Data 13 februarie 2023 22:35:03
Problema Fractii Scor 10
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.99 kb
// brute force
#include <bits/stdc++.h>

using namespace std;

ifstream f("fractii.in");
ofstream g("fractii.out");

int gcd(int a, int b) {
    if (a == 0)
        return b;
    if (b == 0)
        return a;
    int k = 0;
    while ((a & 1) == 0 && (b & 1) == 0) {
        a >>= 1;
        b >>= 1;
        k++;
    }
    while (a != b) {
        if ((a & 1) == 0)
            a >>= 1;
        else if ((b & 1) == 0)
            b >>= 1;
        else if (a > b)
            a = (a - b) >> 1;
        else
            b = (b - a) >> 1;
    }
    return a << k;
}

int have_common_div(int x, int y) {
    return gcd(x, y) != 1;
}

long count_fractions(int n) {
    int count = 2*n - 1;
    for (int i = 2; i <= n; ++i) {
        for (int j = 2; j <= n; ++j) {
            if (!have_common_div(i, j)) {
                count++;
            }
        }
    }
    return count;
}

int main() {
    int n;
    f >> n;
    g << count_fractions(n);
    return 0;
}