1. 程式人生 > >B. Divide Candies Mail.Ru Cup 2018 Round 3 (數學)

B. Divide Candies Mail.Ru Cup 2018 Round 3 (數學)

題目連結:CF

題意:給出n,讓你找出 (x*x+y*y)%m==0的點對(0<x<=n,0<y<=n),問有多少對。

參考官方題解:(x*x+y*y)%m==0,等價於 ((x%m)^2+(y%m)^2)%m==0,設i=x%m,j=y%m,即座標範圍n*n內滿足的點對(x,y),其模值對 (i,j)一定在範圍 m*m中,故我們可以直接暴力 m*m,然後我們看看在n*n範圍包含多少塊m*m,最後處理下多出來的就行了。

 

#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

typedef long long LL;
LL n;
int m;


LL Count(int x1,int x2,int y1,int y2)
{
    LL sum=0;
    for(int i=x1;i<=x2;i++)
    {
        for(int j=y1;j<=y2;j++){
            if((i*i+j*j)%m==0){
                sum++;

            }
        }
    }
    return sum;
}

int main()
{

    while(~scanf("%lld%d",&n,&m))
    {
        LL sum=0;
        LL item=Count(1,m,1,m); ///首先計算m*m滿足條件的有多少個
        sum=sum+item*(n/(LL)m)*(n/(LL)m); ///先計算S

        if(n%m==0){
            printf("%lld\n",sum);continue;
        }




        item=Count(1,m,1,n%m); ///m*(n%m) ///計算S1
        sum+=item*(n/(LL)m);


        item=Count(1,n%m,1,m); ///計算S2
        sum+=item*(n/(LL)m);

        sum+=Count(1,n%m,1,n%m); ///計算S3



        printf("%lld\n",sum);

    }
    return 0;
}