spoj 7001 VLATTICE - Visible Lattice Points(莫比烏斯反演)

Consider a N*N*N lattice. One corner is at (0,0,0) and the opposite one is at (N,N,N). How many lattice points are visible from corner at (0,0,0) ? A point X is visible from point Y iff no other lattice point lies on the segment joining X and Y. 
 
Input : 
The first line contains the number of test cases T. The next T lines contain an interger N 
 
Output : 
Output T lines, one corresponding to each test case. 
 
Sample Input : 




 
Sample Output : 

19 
175 
 
Constraints : 
T <= 50 
1 <= N <= 1000000



題意:問你在(0,0,0)點能看到n*n*n的正方體裏的多少個點,一個點(x,y,z)能被看到,就是(0,0,0)與這個點的連線上沒有其他的點,換句話說,就是gcd(x,y,z) == 1 。

這題是 bzoj2005 的升級版,從二維變成了三維,而且還有不同的是這題需要計算座標軸上的點。

我們用莫比烏斯反演分別求出三個點都不是零的答案,有一個點是零的答案,還有就是在座標軸上的點,有兩個點是零的答案,加起來就是要求的點數了。

我們同樣是設F(n) 爲gcd是n的倍數的個數,f(n)爲gcd是n的個數,

用莫比烏斯反演求出 f(1)

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;

const int maxn = 1e6 + 10;
int p[maxn/10];
int flag[maxn];
int mu[maxn];
int cnt = 0;
void init()
{
    int i,j;
    mu[1] = 1;
    for(i=2;i<maxn;i++)
    {
        if(!flag[i])
        {
            p[cnt++] = i;
            mu[i] = -1;
        }
        for(j=0;j<cnt&&p[j]*i<maxn;j++)
        {
            flag[p[j]*i] = 1;
            if(i % p[j] == 0)
            {
                mu[p[j]*i] = 0;
                break;
            }
            mu[p[j]*i] = -mu[i];
        }
    }
}

int main(void)
{
    int T,n,i,j;
    init();
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        LL sum1 = 0;
        LL sum2= 0;
        for(i=1;i<=n;i++)
        {
            sum1 += (LL)mu[i]*(n/i)*(n/i)*(n/i);
            sum2 += (LL)mu[i]*(n/i)*(n/i);
        }
        LL ans = sum1 + sum2*3 + 3;
        printf("%lld\n",ans);
    }

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章