8 May 2024 (Basic) — Closest Multiple of Y to X

E · easyP · Verified PYQ

Given two integers X and Y, find the multiple of Y that is closest to X. If there are two equally close multiples, return the larger one.

-10**5 < x < 10**5, Y > 0
Input
15
4
Output
16
lower = (x//y)\*y, upper = lower+y. Compare abs(x-lower) vs abs(x-upper). Return closer (upper if tie).
Multiples of 4 near 15: 12 and 16. Distance: |15-12|=3, |15-16|=1. Closest = 16.
← 8 May 2024 (Advanced) — Password Validator + Caesar Cipher8 May 2024 Shift 2 — Prime Number Check →
Report an issue with this question