洛谷B2042 判断一个数能否同时被 3 和 5 整除 题解

题目链接:B2042 判断一个数能否同时被 3 和 5 整除

题目描述:

判断一个数 \(n\) 能否同时被 \(3\) 和 \(5\) 整除。

输入格式:

输入一行,包含一个整数 \(n\)。

输出格式:

输出一行,如果能同时被 \(3\) 和 \(5\) 整除输出 YES,否则输出 NO。

数据范围:

\(-10^9<n<10^9\)

很容易想到取模两次,不过很显然这样是效率更低的,除法很慢、常数大。

注意到,如果一个数能同时被 \(3\) 和 \(5\) 整除,那么它一定可以写做 \(3\times 5 \times \cdots\) 的形式

于是我们只需要判断这个数是否能被 \(15\) 整除即可。

时间复杂度 \(O(1)\)

代码:

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f3f3f3f3f
template<typename T> void up(T &x, T y) { x < y ? x = y : 0; }
template<typename T> void down(T &x, T y) { x > y ? x = y : 0; }
#define rep(i, a, b) for(int i = (a), i##END = (b); i <= i##END; i++)
#define Rep(i, a, b) for(int i = (a), i##END = (b); i >= i##END; i--)
#define N ((int)())

int x;
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    // freopen("check.in","r",stdin);
    // freopen("check.out","w",stdout);
    cin >> x; cout << ((x % 15 == 0) ? "YES" : "NO");
    // if(x % 3 == 0 && x % 5 == 0) cout << "YES"; else cout << "NO";
    // if((x / 3 * 3 == x) && (x / 5 * 5 == x)) cout << "YES"; else cout << "NO";
    return 0;
}