(数学题) Counting

问题描述:

描述

      Given many integers, find out the number of triples (a, b, c) which satisfy a, b, c are co-primed each other or are not co-primed each other. In a triple, (a, b, c) and (b, a, c) are considered as same triple.

输入

     The first line contains a single integer T (T <= 15), indicating the number of test cases.In each case, the first line contains one integer n (3 <= n <= 1000), second line contains n integers d (1 <= d < 105) separated with space.

输出

      For each test case, output an integer in one line, indicating the number of triples.

样例输入



2 3 5 7 11 13

样例输出

20


思路. 本题意在找出所有的三元组,满足:

        1 三个数都互质

         2 三个数都不互质


         换一种思路:

         当三元组中存在一个或两个数对不互质时,不满足条件 .


         假设a 为与元素i互质的元素个数,b为与元素i不互质的元素个数, 那么包含元素i 的,不满足条件的三元组共a*b个 。


  1.       需通过观察可知, 当一次求完a*b累加后,正好多算了一倍。 也就是结果应为 : 总情况数 - sum(a*b)/2;

       代码:

   #include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <algorithm>
#include <utility>
#include <cstring>
using namespace std;
int gcd (int v1,int v2)
{
    while(v2){
        int tmp = v2;
        v2 = v1 % v2;
        v1 = tmp;
    }
    return v1;
}
 
int main(int argc, char* argv[])
{
    int t;
    cin >> t;
    while(t--)
    {
        vector<int> num;
        int n;
        cin >> n;
        for(int i=0;i<n;i++)
        {
            int tmp;
            scanf("%d",&tmp);
            num.push_back(tmp);
        }
        int cgcd=0,cngcd=0,total=(n*(n-1)*(n-2)/6),ans=0;;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++)
            if(i!=j){
                if(gcd(num[i],num[j])==1)
                    cgcd++;
                else
                cngcd++;}
            ans+=cgcd*cngcd;
            cgcd=0;cngcd=0;
        }
        cout<< total-ans/2<<endl;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值