Divisible by 3 but Not 9
Programming Basics · C++
TASK
Problem
An integer `n` is given. Print `YES` if it is divisible by 3 but not by 9; otherwise print `NO`.
EXAMPLE
Example
9
NO
LIMITS
Constraints
All values are integers with magnitude at most 10^9.
LEARN
Theory for this problem
+
Logical AND `&&`, OR `||`, and negation `!` combine boolean conditions. Parentheses make the intended grouping explicit.
Connection to “Divisible by 3 but Not 9”: here, intermediate values are best kept in named variables so the formula stays readable and data types remain clear.
NEED HELP?
Hints
+
['Translate the verbal condition into one boolean expression.', 'After solving “Divisible by 3 but Not 9”, verify the algorithm on your own small example and on an allowed boundary case. Print only the required result with no extra text.']
ANSWER
Solution
+
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
long long n;
cin >> n;
cout << ((n % 3 == 0 && n % 9 != 0) ? "YES" : "NO") << '\n';
return 0;
}