首页 > 代码库 > Number Puzzle
Number Puzzle
Given a list of integers (A1, A2, ..., An), and a positive integer M, please find the number of positive integers that are not greater than M and dividable by any integer from the given list.
Input
The input contains several test cases.
For each test case, there are two lines. The first line contains N (1 <= N <= 10) and M (1 <= M <= 200000000), and the second line contains A1, A2, ..., An(1 <= Ai <= 10, for i = 1, 2, ..., N).
Output
For each test case in the input, output the result in a single line.
Sample Input
3 2
2 3 7
3 6
2 3 7
Sample Output
1
4
分析:1~m中至少能被列表里其中一个数整除的数的个数;
容斥即可,注意列表中的数不一定互质,所以要求lcm;
代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <climits>#include <cstring>#include <string>#include <set>#include <bitset>#include <map>#include <queue>#include <stack>#include <vector>#define rep(i,m,n) for(i=m;i<=n;i++)#define mod 1000000007#define inf 0x3f3f3f3f#define vi vector<int>#define pb push_back#define mp make_pair#define fi first#define se second#define ll long long#define pi acos(-1.0)#define pii pair<int,int>#define sys system("pause")const int maxn=1e5+10;using namespace std;inline ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);}inline ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;}inline void umax(ll &p,ll q){if(p<q)p=q;}inline void umin(ll &p,ll q){if(p>q)p=q;}inline ll read(){ ll x=0;int f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f;}int n,m,k,t,fac[10];int main(){ int i,j; while(~scanf("%d%d",&n,&m)) { rep(i,0,n-1)scanf("%d",&fac[i]); int ret=0; rep(i,1,(1<<n)-1) { int now=1,cnt=0; rep(j,0,n-1) { if(i&(1<<j)) { cnt++; now=now*fac[j]/gcd(now,fac[j]); } } if(cnt&1)ret+=m/now; else ret-=m/now; } printf("%d\n",ret); } return 0;}
Number Puzzle
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。