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) = 3because1is false,1+1is false, but1+1+1is true. Therefore3is returned.f(5,3) = 6because5is false, but5+1is true. Therefore6is returned.f(9,3) = 9because9is already a multiple of 3.f(12,5) = 15because12is false,12+1is false,12+2is false, but12+3is true. Therefore15is 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 code-golf 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.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## 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 ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
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],
link: a.share_link,
});
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;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
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)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 500px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
-
9\$\begingroup\$ 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." \$\endgroup\$flawr– flawr2019年12月06日 08:50:50 +00:00Commented Dec 6, 2019 at 8:50
45 Answers 45
Python, 17 bytes
lambda a,b:a+-a%b
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
cV :Implicit input of integers U & V
cV :Round U up to the nearest multiple of V
With input as an array:
rc
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
_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
ôV ævV :Implicit input of integers U & V
ôV :Range [U,U+V]
æ :Get first element
vV : Divisible by V
-
\$\begingroup\$ Your description bascially repeats the task. I don't know japt, is it possible to describe what each character does? \$\endgroup\$findusl– findusl2019年12月06日 16:56:07 +00:00Commented Dec 6, 2019 at 16:56
-
2\$\begingroup\$ @findusl, "full" explanation added! \$\endgroup\$Shaggy– Shaggy2019年12月06日 17:06:35 +00:00Commented Dec 6, 2019 at 17:06
Intcode (day 5), (削除) 70 (削除ここまで) (削除) 66 (削除ここまで) 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
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.
Download and test ROUNDMY.COM.
MATL, 4 bytes
:ien
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
-
3\$\begingroup\$ Shouldn't the stack after
Rangebe [1 2 3 4 5 6 7 8 9 10 11 12] ? \$\endgroup\$Galen Ivanov– Galen Ivanov2019年12月06日 12:01:23 +00:00Commented Dec 6, 2019 at 12:01 -
1\$\begingroup\$ @Galen Yes, thank you! Corrected \$\endgroup\$Luis Mendo– Luis Mendo2019年12月06日 19:58:26 +00:00Commented Dec 6, 2019 at 19:58
-
\$\begingroup\$ 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 afloor division. Both of wich are more compact expressions. \$\endgroup\$Raserhin– Raserhin2019年12月06日 09:04:49 +00:00Commented Dec 6, 2019 at 9:04 -
1\$\begingroup\$
a/-b*-balso works, and is slightly more readable, I think? \$\endgroup\$Neil– Neil2019年12月06日 21:13:20 +00:00Commented Dec 6, 2019 at 21:13 -
1\$\begingroup\$ @Neil - Readability?!? Blasphemy! :) \$\endgroup\$Chas Brown– Chas Brown2019年12月06日 22:59:46 +00:00Commented Dec 6, 2019 at 22:59
C++ (gcc), (削除) 43 (削除ここまで) (削除) 41 (削除ここまで) (削除) 40 (削除ここまで) (削除) 36 (削除ここまで) 25 bytes
#define f(a,b)(b-a%b)%b+a
Saved 4 bytes thanks to @Neil!!!
Saved 11 bytes thanks to @AZTECCO!!!
-
\$\begingroup\$ -4 bytes:
(b-a%b)%b+a\$\endgroup\$Neil– Neil2019年12月07日 01:02:35 +00:00Commented Dec 7, 2019 at 1:02 -
\$\begingroup\$ @Neil Thanks so much - absolutely brilliant! \$\endgroup\$Noodle9– Noodle92019年12月07日 01:22:12 +00:00Commented Dec 7, 2019 at 1:22
-
-
\$\begingroup\$ @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 \$\endgroup\$AZTECCO– AZTECCO2019年12月07日 12:57:45 +00:00Commented Dec 7, 2019 at 12:57
-
\$\begingroup\$ @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! \$\endgroup\$Noodle9– Noodle92019年12月07日 14:26:44 +00:00Commented Dec 7, 2019 at 14:26
-
\$\begingroup\$
a-(a%b||b)+b=b-(a%b||b)+a=(b-a%b)%b+ato save a byte. \$\endgroup\$Neil– Neil2019年12月07日 01:06:47 +00:00Commented Dec 7, 2019 at 1:06 -
\$\begingroup\$ Wasn't enough though, someone's come up with a 15-byter! \$\endgroup\$Neil– Neil2019年12月09日 22:43:24 +00:00Commented Dec 9, 2019 at 22:43
C (gcc), (削除) 47 (削除ここまで) (削除) 31 (削除ここまで) 25 bytes
f(a,b){a=a%b?f(++a,b):a;}
-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
-
\$\begingroup\$ You can save 1 with ternary Try it online! \$\endgroup\$AZTECCO– AZTECCO2019年12月06日 17:58:28 +00:00Commented Dec 6, 2019 at 17:58
-
-
\$\begingroup\$ Try it online! using Tcc and a different approach \$\endgroup\$AZTECCO– AZTECCO2019年12月06日 21:03:36 +00:00Commented Dec 6, 2019 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.
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.
-
3\$\begingroup\$ Welcome to the site! \$\endgroup\$2019年12月07日 23:15:08 +00:00Commented Dec 7, 2019 at 23:15
-
\$\begingroup\$ 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. \$\endgroup\$Exalted Toast– Exalted Toast2019年12月08日 00:25:26 +00:00Commented Dec 8, 2019 at 0:25
-
\$\begingroup\$ Okay listen, just 'cause you're right... \$\endgroup\$Exalted Toast– Exalted Toast2019年12月08日 02:45:52 +00:00Commented Dec 8, 2019 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
Retina 0.8.2, 28 bytes
\d+
$*
r`1+(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.
Red, 31 bytes
func[a b][round/to/ceiling a b]
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]
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.
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).
-
1\$\begingroup\$ Glad you enjoyed it! I find simple challenges seem to capture folks' imaginations and are more likely to take off than something overcomplicated. --AJFaraday \$\endgroup\$user85052– user850522019年12月08日 01:47:38 +00:00Commented Dec 8, 2019 at 1:47
Charcoal, 10 bytes
×ばつθ÷Nθ
Try it online! Link is to verbose version of code. Takes \$ b \$ first and \$ a \$ second. Explanation:
≔±Nθ
Input \$ b \$, negate it, and save the result.
×ばつθ÷Nθ
Input \$ a \$ and compute \$ -b \lfloor \frac a {-b} \rfloor \$, then cast to string for implicit print.
-
\$\begingroup\$ For those of you counting, this was my 3000th answer! \$\endgroup\$Neil– Neil2019年12月11日 12:10:52 +00:00Commented Dec 11, 2019 at 12:10
GolfScript, 6 bytes
.~)@%+
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}
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).