您的位置:首页 > 其它

【51Nod】1284 - 2 3 5 7的倍数(容斥原理 & 二进制优化)

2016-10-19 21:55 357 查看
题目链接:点击打开题目

1284 2 3 5 7的倍数


基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题


 收藏


 关注

给出一个数N,求1至N中,有多少个数不是2 3 5 7的倍数。 例如N = 10,只有1不是2 3 5 7的倍数。

Input
输入1个数N(1 <= N <= 10^18)。


Output
输出不是2 3 5 7的倍数的数共有多少。


Input示例
10


Output示例
1


用容斥原理最方便,要不估计要TLE的吧。

代码如下:

#include <cstdio>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
int main()
{
LL n;
int num[4] = {2,3,5,7};
scanf ("%lld",&n);
LL ans = n;
int i = 1;
while (i < (1 << 4))
{
int mul = 1;
int ant = 0;
int t = i;
for (int j = 0 ; j < 4 ; j++)
{
if ((1 << j) & i)
{
ant++;
mul *= num[j];
}
}
if (ant & 1) //奇数
ans -= n / mul;
else
ans += n / mul;
i++;
}
printf ("%lld\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: