牛客網-計數器

【題目描述】
有一個計數器,計數器的初始值爲0,每次操作你可以把計數器的值加上a1,a2,...,an中的任意一個整數,操作次數不限(可以爲0次),問計數器的值對m取模後有幾種可能。
【輸入描述】
第一行兩個整數n,m
接下來一行n個整數表示a1,a2,...,an, 1≤n≤100 ,1≤m,a1,a2,...,an≤1000000000
【輸出描述】
輸出一個整數表示答案
【示例】
【輸入】
3 6
6 4 8
【輸出】
3

【思路分析】

先介紹一下 裴蜀定理

任意整數a,b,以及a和b的最大公約數d,任意整數x,y, 若m = a*x+b*y,則m一定爲d的整數倍。特別的,一定存在整數x,y,使得a*x+b*y = d 成立。推論:整數a,b互質的充要條件是存在x,y使得 a*x + b*y = 1 成立。

回到題目中,若a_1,a_2,a_3,...,a_n互質,則存在整數x_1,x_2,x_3,...,x_n使得a_1*x_1 + a_2*x_2 + ... + a_n*x_n = 1 = gcd(a_1,a_2,...,a_n)成立。但題目中並沒有a_1,a_2,a_3,...,a_n互質的前提,所以,存在整數x_1,x_2,x_3,...,x_n使得a_1*x_1 + a_2*x_2 + ... + a_n*x_n = gcd(a_1,a_2,...,a_n)成立。

存在x_1,x_2,x_3,...,x_n, k使得a_1*x_1 + a_2*x_2 + ... + a_n*x_n + m*k = gcd(a_1,a_2,...,a_n,m)成立。

兩邊同時對m取模,(a_1*x_1 + a_2*x_2 + ... + a_n*x_n)\mod m = gcd(a_1,a_2,...,a_n,m) \mod m

又由於gcd(a_1,a_2,...,a_n,m)m的因數 ,

所以,m/gcd(a_1,a_2,...,a_n,m)爲取模後的結果的個數。

【代碼】

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<memory.h>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<array>
#include<deque>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define mem(array)  memset((array),0,sizeof((array)))
#define Qsort(array,len,cmp) qsort(array,len,sizeof(array[0]),cmp)
#define inf 0x7fffffff
#define MAXN 10+10000
using namespace std;

int gcd(int x,int y)
{
    int t;
    t = x > y ? x : y;
    x = x > y ? y : x;
    y = t;
    while(y % x){
        t = y % x;
        y = x;
        x = t;
    }
   return x;
}


int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",tdout);
    int n,m;
    while(cin>>n>>m){
        int ans = m;
        int x;
        for(int i = 0; i < n; ++i){
            scanf("%d",&x);
            ans = gcd(x,ans);
        }
        cout<< m/ans << endl;
    }
    return 0;
}

 

題目來源 牛客網

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