MATLAB Answers


How to find next number divisible by n

Asked by Pedro Oliveira on 22 Nov 2017
Latest activity Commented on by Pedro Oliveira on 22 Nov 2017
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.


Sign in to comment.

2 Answers

Answer by Torsten
on 22 Nov 2017
 Accepted Answer

b = a + (n - rem(a,n))
Best wishes

  1 Comment

This works! Thank you!

Sign in to comment.

Answer by David J. Mack on 22 Nov 2017

How about
b = n * ceil(a / n)
Greetings, David

  1 Comment

This also works! Thank you! I didn't know the ceil function but I'll look into it.

Sign in to comment.