# Round up my number

Sandbox

Given two positive integers a and b, return the smallest multiple of b that is greater than or equal to a.

## Examples

Definitions: true = is a multiple of b, false = is not a multiple of b.

• f(1,3) = 3 because 1 is false, 1+1 is false, but 1+1+1 is true. Therefore 3 is returned.

• f(5,3) = 6 because 5 is false, but 5+1 is true. Therefore 6 is returned.

• f(9,3) = 9 because 9 is already a multiple of 3.

• f(12,5) = 15 because 12 is false, 12+1 is false, 12+2 is false, but 12+3 is true. Therefore 15 is returned.

## Rules

• Input/output can be given by any convenient method.
• You can print it to STDOUT or return it as a function result.
• Either a full program or a function are acceptable.
• Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
• Standard loopholes are forbidden.
• This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

## Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes


If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes


You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes


/* Configuration */

var QUESTION_ID = 196683; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});
else console.log(body);
});

valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();

languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body {
text-align: left !important;
display: block !important;
}

width: 290px;
float: left;
}

#language-list {
width: 500px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• I think from your wording it is not so clear what actually should be returned. I'd just rephrase the challenge to something like "Given two positive integers a and b, return the smallest number that is at least as big as a which is also a multiple of b." – flawr Dec 6 '19 at 8:50

# Python, 17 bytes

lambda a,b:a+-a%b


Try it online!

Since this doesn't use division, it works for both Python 2 and 3. Note that we can't cut out the + sign because a-a%b does a-(a%b), whereas we want to do(-a)%b and add that to a. We could also write it as -a%b+a.

# Japt, 2 bytes

cV


Try it

cV     :Implicit input of integers U & V
cV     :Round U up to the nearest multiple of V


With input as an array:

rc


Try it

rc     :Implicit input of array
r      :Reduce by
c     :Rounding the first element up to the nearest multiple of the second


## Less Trivial!, 6 bytes

_vV}aU


Try it

_vV}aU     :Implicit input of integers U & V
_          :Function taking an integer Z as input
vV        :  Is Z divisible by V?
}       :End function
aU     :Starting from U, return the first integer that returns true when passed through that function

ôV ævV


Try it

ôV ævV     :Implicit input of integers U & V
ôV         :Range [U,U+V]
æ       :Get first element
vV     :  Divisible by V

• Your description bascially repeats the task. I don't know japt, is it possible to describe what each character does? – findusl Dec 6 '19 at 16:56
• @findusl, "full" explanation added! – Shaggy Dec 6 '19 at 17:06

## Intcode (day 5), 7066 64 bytes

3,0,3,2,102,-1,2,4,1,0,4,0,1,1,8,1,7,9,0,5,5,5,14,2,1,2,0,4,0,99


Try it online!

Intcode is a programming language invented for Advent of Code 2019. It was first introduced on day 2, then further expanded upon on day 5, which is the version used here.

Since on PPCG, languages are defined by their interpreters, I am using the interpreter that I wrote for my day 5 solution (which was written before this challenge).

Explanation:

3,0,          store first input in cell 0
3,2,          store second input in cell 2
(cell 1 is a counter, because it's already initialized to zero)
102,-1,2,4,   negate the second input and store in cell 4

(begin loop)
1,0,4,0,      subtract the second input from the first input
1,1,8,1,      increment the counter (by adding cell 8)
7,9,0,5,      if the first input is greater than zero (cell 9)...
5,5,14,       ... jump to the beginning of the loop (reusing the cell 8 reference)

2,1,2,0,      multiply the counter by the second input
4,0,99        output and quit


# x86 Machine Code, 7 bytes

Since x86 integer division instructions do only floor rounding, this uses the formula: f(a,b) = floor((a+b-1)/b)*b to accomplish ceiling rounding.

02 C3   ADD  AL, BL     ; a = a + b
48      DEC  AX         ; a = a - 1
F6 F3   DIV  BL         ; a = a / b
F6 E3   MUL  BL         ; a = a * b


Input is in AL and BL, output is AL.

Testing

Here is output from a test program for PC DOS that takes interactive input.

# MATL, 4 bytes

:ien


Try it online!

### Explanation

Consider inputs 12, 5.

     % Implicit input
:    % Range
% STACK: [1 2 3 4 5 6 7 8 9 10 11 12]
i    % Input
% STACK: [1 2 3 4 5 6 7 8 9 10 11 12], 5
e    % Reshape as a matrix with that number of rows, padding with zeros
% STACK: [1  6 11;
2  7 12;
3  8  0;
4  9  0;
5 10  0]
n    % Number of elements
% STACK: 15
% Implicit display

• Shouldn't the stack after Range be [1 2 3 4 5 6 7 8 9 10 11 12] ? – Galen Ivanov Dec 6 '19 at 12:01
• @Galen Yes, thank you! Corrected – Luis Mendo Dec 6 '19 at 19:58

# Octave, 17 bytes

Same method as this JS answer:

@(a,b)ceil(a/b)*b


Try it online!

# Python 2, 2320 18 bytes

lambda a,b:-a/b*-b


Try it online!

2 bytes thanks to tsh

• My guess is that is not necessary as Python 2 division (/) actually returns an integer itself. And in Python 3 you can directly use // as a floor division. Both of wich are more compact expressions. – Raserhin Dec 6 '19 at 9:04
• a/-b*-b also works, and is slightly more readable, I think? – Neil Dec 6 '19 at 21:13
• @Neil - Readability?!? Blasphemy! :) – Chas Brown Dec 6 '19 at 22:59

a%b=a+mod(-a)b


Try it online!

# C++ (gcc), 43414036 25 bytes

#define f(a,b)(b-a%b)%b+a


Try it online!

Saved 4 bytes thanks to @Neil!!!

Saved 11 bytes thanks to @AZTECCO!!!

• -4 bytes: (b-a%b)%b+a – Neil Dec 7 '19 at 1:02
• @Neil Thanks so much - absolutely brilliant! – Noodle9 Dec 7 '19 at 1:22
• 25 using #macro – AZTECCO Dec 7 '19 at 12:56
• @Neil the same solution I suggested here codegolf.stackexchange.com/a/196710/84844 in the last comment, which is basically a port of xnor solution – AZTECCO Dec 7 '19 at 12:57
• @AZTECCO Wow! I was assuming we're stuck with the first run of bytes as the shortest possible in C++ but you came up with a way forwards! – Noodle9 Dec 7 '19 at 14:26

# JavaScript (Node.js), 17 bytes

a=>b=>a+(b-a%b)%b


Try it online!

• a-(a%b||b)+b=b-(a%b||b)+a=(b-a%b)%b+a to save a byte. – Neil Dec 7 '19 at 1:06
• Wasn't enough though, someone's come up with a 15-byter! – Neil Dec 9 '19 at 22:43

# Jelly, 3 bytes

÷Ċ×


Try it online!

Simply divide, ceiling, multiply.

# C (gcc), 4731 25 bytes

f(a,b){a=a%b?f(++a,b):a;}


Try it online!

-16 bytes thanks to A̲̲ (forgot that return types and parameters would default to int if not defined, whoops!)

-6 thanks to AZTECCO for using a ternary and making the function recursive

• You can save 1 with ternary Try it online! – AZTECCO Dec 6 '19 at 17:58
• 25 – AZTECCO Dec 6 '19 at 20:13
• Try it online! using Tcc and a different approach – AZTECCO Dec 6 '19 at 21:03

# Wolfram Language (Mathematica), 7 bytes

Ceiling


Just pointing out that Mathematica's builtin, which is most commonly called with one argument, actually does exactly the desired operation when called with two arguments.

## Brainfuck, 52 49 bytes

Thanks to Jo King for finding a bug, helping fix it with some extra golfing.

,>>,<<[>+>->+<[>]>[<+>-]<<[<]>-]>>>[<[-<+>]>,]<<.


Input and output is in character codes.

Try it online!

Explanation

,>>,<<                     [>a, 0,     b,   0]
[>+>->+<[>]>[<+>-]<<[<]>-] [>0, a, b-a%b, a%b]
>>>[<[-<+>]>,]             If a%b is nonzero, add b-a%b to a, and clear a%b
<<.                        Output a+(b-a%b)


Modulus algorithm is straight from the esolang list of brainfuck algorithms.

• Welcome to the site! – Wheat Wizard Dec 7 '19 at 23:15
• Yikes. Yeah, somehow it slipped my mind "outputting a null won't matter" when I'm using character codes. Will update the code to your version. – Exalted Toast Dec 8 '19 at 0:25
• Okay listen, just 'cause you're right... – Exalted Toast Dec 8 '19 at 2:45

# JavaScript (V8), 22 bytes

This is the function $$\(a,b) \mapsto \left\lceil \frac{a}{b} \right\rceil b\$$.

a=>b=>Math.ceil(a/b)*b


Try it online!

# R, 20 bytes

function(a,b)a+-a%%b


Try it online!

# K (oK), 8 bytes

{x+y!-x}


Try it online!

Another port of xnor's Python answer.

# Retina 0.8.2, 28 bytes

\d+
$* r1+(\2*) (1+)$1$2 1  Try it online! Link includes test cases. Explanation: \d+$*


Convert the inputs to unary.

r


Process this stage from right-to-left, so that \2 gets to match $$\ b \$$ first, allowing us to refer to it when matching within $$\ a \$$.

1+(\2*) (1+)


Match $$\ b \$$ in \2, then as many copies of $$\ b \$$ as we can, without completely exhausting $$\ a \$$. \1 thus matches $$\ b \lfloor \frac {a - 1} b \rfloor = b \lceil \frac {a - b} b \rceil \$$

$1$2


Add that to $$\ b \$$ to give $$\ b \lceil \frac a b \rceil \$$.

1


Convert to decimal.

# Ruby, 13 bytes

->a,b{-a%b+a}


Try it online!

# Red, 31 bytes

func[a b][round/to/ceiling a b]


Try it online!

Just a built-in round with refinements to, which scales the first argument according to the second, and ceiling, which indicates the direction.

# Red, 25 bytes

func[a b][0 - a // b + a]


Try it online!

A port of xnor's Python answer. Don't forget to upvote his answer!

# Prolog (SWI) + CLPFD, 30 bytes

f(R,X,Y):-R#=_*Y,R-Y#<X,R#>=X.


Try it online!

f(R,X,Y)


f is a predicate taking in a variable R, and two integers X and Y.

The CLPFD constraints are expressed using the #-prefixed operators. , means and, so f is true iff all these constraints are satisfied, i.e.,

1) R#=_*Y R is a multiple of Y , and

2) R-Y#<X R-Y < X , and

3) R#>=X R >= X .

# SimpleTemplate, 61 bytes

This was quite fun! Sadly, I had to do the dumb way :(

{@fn F A,B}{@whileA is notmultipleB}{@incA}{@/}{@returnA}{@/}


Creates a function that iterates until it finds a number that's multiple of the 2nd number.

This was actually way smaller than doing it without a function.

Ungolfed:

{@fn F numberA, numberB}
{@while numberA is not multiple of numberB}
{@inc by 1 numberA}
{@/}
{@return numberA}
{@/}


Should be mostly straightforward.

You can see it running on https://ideone.com/MR7t1E (golfed version only).

• Glad you enjoyed it! I find simple challenges seem to capture folks' imaginations and are more likely to take off than something overcomplicated. --AJFaraday – user85052 Dec 8 '19 at 1:47

# Charcoal, 10 bytes

≔±ＮθＩ×θ÷Ｎθ


Try it online! Link is to verbose version of code. Takes $$\ b \$$ first and $$\ a \$$ second. Explanation:

≔±Ｎθ


Input $$\ b \$$, negate it, and save the result.

Ｉ×θ÷Ｎθ


Input $$\ a \$$ and compute $$\ -b \lfloor \frac a {-b} \rfloor \$$, then cast to string for implicit print.

• For those of you counting, this was my 3000ᵗʰ answer! – Neil Dec 11 '19 at 12:10

# GolfScript, 6 bytes

.~)@%+


Try it online!

Function which consumes A and B from the stack, assuming B is below A.

### Explanation:

           #Example input: A = 12, B = 5          stack is  5  12
.~)        #Duplicate A and negate the duplicate  stack is  5  12 -12
@       #Pull 3rd from top to top              stack is 12 -12   5
%      #Second to top mod top                 stack is 12 3
+     #Add remaining values                  stack is 15


# Javascript (ES6), 19 bytes

a=>b=>a%b?a-a%b+b:a


Naive attempt, pretty sure this can be golfed further.

# Java, 99 bytes

static int r(int a,int b){int t=a%b<1||b%a<1?a:r(a+1,b);return t;}


## JavaScript, 15 bytes

a=>b=>--a+b-a%b


More expressively, the answer is a => b => a + b-((a-1)%b) - 1, but by decrementing a we can handle both the "subtract one" steps at once, saving a couple of bytes. Then we just get lucky with operator presidencies.

## Perl 5, (111 bytes with footer) 52 bytes

sub f{($a,$b)=@_;$c=$b;$c++until!($c%$b)&&$c>=$a;$c}

Try it online!

Takes a and b as arguments to a subroutine named f and increases $c until it is both a multiple of $b and greater than or equal to $a. Then returns $c (the last value evaluated in a subroutine is the return value).

# Java (JDK), 15 bytes

b->a->--a+b-a%b


Try it online!

# J, 6 bytes

]*>.@%


Try it online!

]         the right argument
*        multiplied by
>.@     the ceiling of
%    the left argument dividided by the right one


If we can swap the order of the aruments:

# J, 5 bytes

]+[|-


Try it online!