Cod sursa(job #2768718)

Utilizator DragosC1Dragos DragosC1 Data 11 august 2021 22:34:23
Problema Pairs Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.43 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
using namespace std;

int fr[1000001];
int n;
int Max;
long long rez;

void read() {
    int i, x;
    ifstream f("pairs.in");
    f >> n;
    for (i = 1; i <= n; i++) {
        f >> x;
        if (x > Max)
            Max = x;
        fr[x]++;
    }
    f.close();
}

bitset<1021> e;
int pr[1021], lung;

void Ciur() {
    int i, j;
    for (i = 2; i <= 1020; i++)
        if (!e[i])
            for (j = 2; i * j <= 1020; j++)
                e[i * j] = 1;
    for (i = 2; i <= 1020; i++)
        if (!e[i])
            pr[lung++] = i;
}

void solve() {
    int i, j, nr, x, cnt;

    Ciur();

    rez = n * (n - 1) / 2;

    for (i = 2; i <= Max; i++) {
        x = i, cnt = 0;
        for (j = 0; pr[j] * pr[j] <= x; j++) {
            if (x % pr[j] == 0) {
                x /= pr[j];
                cnt++;
            }
        }  
        if (x > 1) {
            x = 1;
            cnt++;
        }
        if (x != 1)
            continue;
        nr = 0;
        nr += min(1, fr[i]);
        for (j = 2; i * j <= Max; j++)
            nr += fr[i * j];
        if (cnt & 1)
            rez -= nr * (nr - 1) / 2;
        else rez += nr * (nr - 1) / 2;
    }
}

void output() {
    ofstream g("pairs.out");
    g << rez;
    g.close();
}

int main() {
    read();
    solve();
    output();
    return 0;
}