Codeforces839D Winter is here (数论:容斥原理)

D. Winter is here
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.

He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan ifi1 < i2 < i3 < ... < ik and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan k·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans.

Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7).

Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.

Input

The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his soldiers.

Output

Print one integer — the strength of John Snow's army modulo 1000000007 (109 + 7).

Examples
input
3
3 3 1
output
12
input
4
2 3 4 6
output
39
Note

In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12

题意:

给出一些数,求其中GCD不为1的数的序列长度乘以对应的GCD之和;emmmm。。主要还是看例子看懂的。

思路:

首先要知道有n个数的话,那么这n个数组合长度不为零的组合一共有n*(2^(n-1))种,知道这个规律后,接下来我们就假设F(x)就是这个公式的返回值。还需要考虑一种情况,例如如果GCD为4的时候,但这种情况下在2中会多记录4中的情况。这时候就遵循容斥原理,此时2中的数量就等于F(2) - F(4) - F(8) ....-F(2*n),即某个数的情况数和就等于F(x)减去x倍数的F。有了这条规律就好做了。

代码:

#include
using namespace std;
const int  MAX_N = 1e6 + 9;
const int MOD = 1e9+7;
long long vec[MAX_N];
long long sum[MAX_N];
long long my_pow(long long x,int k)
{
    long long res = 1;
    while(k>0)//发现原来while(k)的用法只会在k=0的时候才break,在k<0的时候并不会break。!
    {
        k--;
        res *= x;
        res %= MOD;//emmm。这个MOD没有加上卡了我好久
    }
    return res;
}
int main()
{
    int N,M,T;
    while(~scanf("%d",&N))
    {
        memset(vec,0,sizeof(vec));
        memset(sum,0,sizeof(sum));
        int maxn = -1;
        for(int i=0; i=2; i--)
        {
            //if(vec[i]) 
            //这里千万不能写这条,因为比方说现在有GCD为4和8的集合那么vec[2]
            //就为0,但是其实GCD为2的集合数量并不为0
            long long tot = 0;
            for(int j=i; j<=maxn; j+=i)
            {
                sum[i] -= sum[j];
                tot += vec[j];
            }
            sum[i] += (tot*my_pow(2,tot-1)+ MOD) %MOD; //要加上MOD,因为sum减去后有可能为负值
            ans += (i*sum[i])%MOD;
            ans = (ans+MOD)%MOD;
        }
        cout<


你可能感兴趣的:(CodeForces)