You are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x>1) that n is divisible by x and x is odd).
For example, if n=6, then there is x=3. If n=4, then such a number does not exist.
Input
The first line contains one integer t (1≤t≤104) — the number of test cases. Then t test cases follow.
Each test case contains one integer n (2≤n≤1014).
Please note, that the input for some test cases won’t fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language.
Output
For each test case, output on a separate line:
“YES” if n has an odd divisor, greater than one;
“NO” otherwise.
You can output “YES” and “NO” in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input:
6
2
3
4
5
998244353
1099511627776
Output:
NO
YES
NO
YES
YES
NO
思路:
首先题目大致意思是给一个整数,然后判断它是否存在除了1以外的其他奇数因子。
然后我们开始分析:
在数学中,我们都知道有如下规律:
偶数 ∗ 偶数 = 偶数;
奇数 ∗ 偶数 = 偶数;
偶数 ∗ 奇数 = 偶数;
奇数 ∗ 奇数 = 奇数.
所以,假如输入的数是奇数,那么一定存在除1之外的奇数因子。
那输入的数是偶数该怎么判断?
通过上面的规律,我们不难发现,当且仅当n是2的某一次幂时n才不存在除1之外的奇数因子,这也与2是唯一的偶质数有关。
所以题目就变成了判断输入的n是否是2的某一次幂。
AC代码:
#include <iostream>
#include <cstdio>
using namespace std;
int main(void)
{
int t;
scanf("%d", &t);
while (t--)
{
long long n;
scanf("%lld", &n);
// printf("%lld\n", n);
if ((n & (n - 1)) == 0) puts("NO");
else puts("YES");
}
return 0;
}
关键步骤解释:
&是按位与运算
有如下运算法则:
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
1 & 1 = 1
假如一个数是2的某一次幂,例如4,其对应二进制数是100,3对应二进制数是011
4&3 = 0
故判断一个数n是否是2的某一次幂可以用n&(n-1) 是否等于0去判断。