容斥原理的应用
#include
<
iostream
>
#include < string >
using namespace std;
int a[ 12 ];
int b[ 12 ];
int n, m;
double total;
int gcd( int x, int y)
{
return y==0?x:gcd(y,x%y);
}
int gsm( int x, int y)
{
return (x*y)/gcd(x,y);
}
void dfs( int u, int sum, int cnt, int vn)
{
int i;
if(cnt==vn)
{
total += m/sum;
return;
}
for (i=u; i<n; ++i)
{
dfs(i+1, gsm(sum,b[i]), cnt+1, vn);
}
}
int main()
{
int i, j, temp;
double ans;
while (cin >> n >> m)
{
memset(a, 0, sizeof(a));
for (i=0; i<n; ++i)
{
scanf("%d", &temp);
a[temp] = 1;
}
n = 0;
for (i=1; i<=10; ++i)
{
if(a[i] && i<=m)
b[n++] = i;
}
ans = 0;
for (i=1; i<=n; ++i)
{
total = 0;
dfs(0,1,0,i);
if(i%2!=0)
ans += total;
else
ans -= total;
}
printf("%.0lf ",ans);
}
return 0;
}
#include < string >
using namespace std;
int a[ 12 ];
int b[ 12 ];
int n, m;
double total;
int gcd( int x, int y)
{
return y==0?x:gcd(y,x%y);
}
int gsm( int x, int y)
{
return (x*y)/gcd(x,y);
}
void dfs( int u, int sum, int cnt, int vn)
{
int i;
if(cnt==vn)
{
total += m/sum;
return;
}
for (i=u; i<n; ++i)
{
dfs(i+1, gsm(sum,b[i]), cnt+1, vn);
}
}
int main()
{
int i, j, temp;
double ans;
while (cin >> n >> m)
{
memset(a, 0, sizeof(a));
for (i=0; i<n; ++i)
{
scanf("%d", &temp);
a[temp] = 1;
}
n = 0;
for (i=1; i<=10; ++i)
{
if(a[i] && i<=m)
b[n++] = i;
}
ans = 0;
for (i=1; i<=n; ++i)
{
total = 0;
dfs(0,1,0,i);
if(i%2!=0)
ans += total;
else
ans -= total;
}
printf("%.0lf ",ans);
}
return 0;
}