-1

Is it possible to find the smallest multiplicity of k greater or equal than n without if statement?, in other words smallest number divisible by k greater or equal than n.

I am looking for expression without condition (also without triple operator and so on).

For example,

n = 78, k = 10 -----> 80
n = 80, k =10 -------> 80
n = 13, k = 3 -------> 15
n = 14, k =2 ----> 14
n=13, k = 11 ----> 22
  • Why? is this homework? – DeepSpace Apr 11 at 14:34
0

This can do the trick

x = ((n // k) + (n % k != 0)) * k
0

Abusing the fact that bool can be converted to int:

tests = [(78, 10), (80, 10), (13, 3), (14, 2), (13, 11)]

for n, k in tests:
    print([n, n - n % k + k][int(bool(n % k))])

outputs

80
80
15
14
22

Explanation

[n, n - n % k + k] just creates a list. The "trick" is the indexing we use: if n % k is 0 it means that we want to choose n. Otherwise, int(bool(n % k)) will become 1 which means n - n % k + k will be chosen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.