PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: raysh07
Tester: sushil2006
Editorialist: iceknight1093
DIFFICULTY:
Cakewalk
PREREQUISITES:
None
PROBLEM:
Given an integer N, find the closest multiple of 3 to N.
EXPLANATION:
This is a simple implementation task, with a couple of different solutions.
One solution is to use casework:
- If N is a multiple of 3, the answer is N itself.
- Otherwise, one of N-1 or N+1 will be a multiple of 3, so check both and print whichever one is.
Alternately, since N \leq 10 the answer definitely lies between 0 and 9.
So, you can iterate through all the multiples of 3 between 0 and 9 (namely 0, 3, 6, 9) and check which one of them is closest to N.
TIME COMPLEXITY:
\mathcal{O}(1) per testcase.
CODE:
Editorialist's code (PyPy3)
n = int(input())
if n%3 == 0: print(n)
elif (n+1)%3 == 0: print(n+1)
else: print(n-1)