CF900D:Unusual Sequences(数学)

D. Unusual Sequences
time limit per test 1 second
memory limit per test 256 megabytes
input standard input
output standard output
Count the number of distinct sequences a1, a2, ..., an (1 ≤ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and . As this number could be large, print the answer modulo 109 + 7.

gcd here means the greatest common divisor.

Input
The only line contains two positive integers x and y (1 ≤ x, y ≤ 109).

Output
Print the number of such sequences modulo 109 + 7.

Examples
input
3 9
output
3
input
5 8
output
0
Note
There are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).

There are no suitable sequences in the second test.


题意:将Y分解成若干个数相加,且这些数的GCD为X的方案数。

思路:显然Y必须能被X整除,且这些数都能被X整除,那么我们把Y拆成T=Y/X个X,这T个块可以任意组合,但GCD必须为X。先考虑将T拆成若干个数相加的方案数,用隔板法得pow(2, T-1),这就是GCD为X的倍数的方案数,那么我们减去2*X,3*X......的方案数即可,可以容斥原理实现,不过倒着计算往往会简单一点。
 

# include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1e9+7;
LL a[2000],dp[2000];
LL qmod(LL y)
{
    LL res = 1, two = (LL)2;
    for(;y;y>>=1)
    {
        if(y&1) res = res*two%mod;
        two = two*two%mod;
    }
    return res;
}
int main()
{
    LL x, y;
    int cnt=0;
    scanf("%lld%lld",&x,&y);
    if(y%x) return 0*puts("0");
    for(LL i=1; i<=sqrt(y); ++i)
    {
        if(y%i==0)
        {
            if(i%x==0) a[++cnt] = i;
            if(i*i!=y&&y/i%x==0) a[++cnt] = y/i;
        }
    }
    sort(a+1, a+1+cnt);
    for(int i=cnt; i>0; --i)
    {
        dp[i] = qmod(y/a[i]-1);
        for(int j=i+1; j<=cnt; ++j)
            if(a[j]%a[i]==0)
                dp[i] = ((dp[i]-dp[j])%mod+mod)%mod;
    }
    printf("%lld\n",dp[1]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/c_czl/article/details/88131880