3、心灵治愈(heal.cpp/c/pas)
【问题描述】
给出一个方程:
A1 * X1` + A2 * X2 + …… + An+1 * Xn+1 = 1
其中 Xn+1 为 m,其余的 X 可以为小于等于 m 的任意的正整数,A 可以取任意的整数。
现在的问题是,给出 n 与 m,需要你求出该方程解的方案数,对 1e9+7 取模。
【输入格式】
给出两个数 N 与 M。
【输出格式】
输出一个方案数。
【样例输入 1】
2 3
【样例输出 1】
8
【样例解释 1】
(1, 1, 3), (1, 2, 3), (1, 3, 3), (2, 1, 3),
(2, 2, 3), (2, 3, 3), (3, 1, 3), (3, 2, 3).
【样例输入 2】
8 8
【样例输出 2】
16711680
【数据规模和约定】
对于所有数据 abs(M)<=1e15
题解:
考虑两个变量是不是一个拓展欧几里得算法?
不仿猜想多个变量也是一样的,有解的情况就是所有的数的最大公约数为 1。
对于数学上的证明,有一个叫丢番图方程的……
容斥:
考虑将 m 分解质因数,枚举质因数 t,在 1-m 中就有 m/t 个数是 t 的倍数,考虑用这m/t 个数去填,就有(m/t)^n 种填法,这些方案是不合法的减掉它。但是如果全部减掉又是不对的, 应该要枚举所有的质因数的组合,当选择的质因数个数为奇数时减,偶数时加,时间复杂度为 O(2^z*logn),这里的 z 不超过 15。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define LL long long
const LL mod=1e9+7;
int Pnum=0;
LL prime[1010],n,m;
void divide(LL x)
{
LL now=x;
for(LL i=2;i*i<=x;i++)
if(now%i==0)
{
while(now%i==0)now/=i;
prime[++Pnum]=i;
}
if(now!=1)prime[++Pnum]=now;
}
LL pow(LL x,LL y)
{
x%=mod;
if(y==0)return 1;
if(y==1)return x;
LL t=pow(x,y>>1),ans=t*t%mod;
if(y&1)ans=ans*x%mod;
return ans%mod;
}
LL ans=0;
void dfs(int x,int ch,LL num)
{
if(x==Pnum+1)
{
if(ch&1)
{
ans-=pow(num,n);
ans%=mod;
ans=(ans+mod)%mod;
}
else
{
ans+=pow(num,n);
ans%=mod;
}
return;
}
dfs(x+1,ch,num);
dfs(x+1,ch+1,num/prime[x]);
}
int main()
{
freopen("heal.in","r",stdin);
freopen("heal.out","w",stdout);
scanf("%I64d%I64d",&n,&m);
if(m>0)
{
divide(m);
dfs(1,0,m);
}
printf("%I64d",ans);
}