Mod, Or and Everything

Problem Description
You are given an integer n.
You are required to calculate (n mod 1) or (n mod 2) or … or (n mod (n - 1)) or (n mod n).
The “or” operation means “bitwise OR”.

Input
The first line contains an integer T(1≤T≤5000)representing the
number of test cases.

For each test case, there is an integer n(1≤n≤1012)in one line.

Output
For each test case, print the answer in one line.

Sample Input
5
1
2
3
4
5

Sample Output
0
0
1
1
3

当n为偶数时,设m=n/2-1
当n为奇数时,设m=(n-1)/2
可以发现,n mod i<=m,且当i<=m时,有 n mod (n-i)=i。于是可以得出n mod i取到0~m的所有整数,因此答案会是2^k-1,k的具体值判断一下即可。
换句话说,就是其存在log(n)-1的规律。

#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL T,n;
int main()
{
	scanf("%lld",&T);
	while(T--){
		scanf("%lld",&n);
		if((n&(-n))==n){
			printf("%lld\n",max(0ll,n/2-1));
			continue;
		}
		while((n&(-n))!=n)
			n-=(n&(-n));
		printf("%lld\n",n-1);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值