小美的因子查询
[题目链接](https://www.nowcoder.com/practice/1870e68256794c6aa727c8bb71fd9737)
思路
给定一个正整数 ,判断它是否存在至少一个偶数因子。
分析
一个正整数 存在偶数因子,当且仅当
本身是偶数。
充分性:若 是偶数,则
,而
是偶数,因此
存在偶数因子。
必要性:若 是奇数,则
的所有因子都是奇数(因为两个奇数的乘积仍然是奇数,所以奇数不可能有偶数因子),因此
不存在偶数因子。
综上,只需判断 是否为偶数即可。判断偶数可以用
或位运算
。
复杂度分析
- 时间复杂度:
,其中
是询问次数,每次询问只需常数时间。
- 空间复杂度:
。
代码
#include <iostream>
using namespace std;
int main() {
int q;
scanf("%d", &q);
while (q--) {
long long x;
scanf("%lld", &x);
puts(x % 2 == 0 ? "YES" : "NO");
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
while (q-- > 0) {
long x = sc.nextLong();
sb.append(x % 2 == 0 ? "YES" : "NO").append('\n');
}
System.out.print(sb);
}
}

京公网安备 11010502036488号