How to find next number divisible by n

42 次查看(过去 30 天)
Hi, I have a number 'a' and I want to find the next number 'b' that is divisible by a certain n (if 'a' isn't divisible by n).
Initially I was doing it like below:
b = a + rem(a,n)
But I noticed that it gives the distance to the closest number that is divisible by n. In the specific example of being a = 14 and n = 4, rem(a,n) gives 2 since the closes number divisble by 4 is 12. Thus b will be 14 (not divisible by 4) instead of 16, as originally intended.
Thank you for any help you can provide.

采纳的回答

Torsten
Torsten 2017-11-22
b = a + (n - rem(a,n))
Best wishes
Torsten.

更多回答(1 个)

David J. Mack
David J. Mack 2017-11-22
How about
b = n * ceil(a / n)
Greetings, David
  1 个评论
Pedro Oliveira
Pedro Oliveira 2017-11-22
This also works! Thank you! I didn't know the ceil function but I'll look into it.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by