20
\$\begingroup\$

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.

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>

\$\endgroup\$
  • 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 Dec 6 '19 at 8:50

38 Answers 38

16
\$\begingroup\$

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.

\$\endgroup\$
9
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Your description bascially repeats the task. I don't know japt, is it possible to describe what each character does? \$\endgroup\$ – findusl Dec 6 '19 at 16:56
  • 2
    \$\begingroup\$ @findusl, "full" explanation added! \$\endgroup\$ – Shaggy Dec 6 '19 at 17:06
8
\$\begingroup\$

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

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
\$\endgroup\$
7
\$\begingroup\$

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
\$\endgroup\$
  • 3
    \$\begingroup\$ Shouldn't the stack after Range be [1 2 3 4 5 6 7 8 9 10 11 12] ? \$\endgroup\$ – Galen Ivanov Dec 6 '19 at 12:01
  • 1
    \$\begingroup\$ @Galen Yes, thank you! Corrected \$\endgroup\$ – Luis Mendo Dec 6 '19 at 19:58
6
\$\begingroup\$

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.

enter image description here

Download and test ROUNDMY.COM.

\$\endgroup\$
5
\$\begingroup\$

Octave, 17 bytes

Same method as this JS answer:

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

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Python 2, 23 20 18 bytes

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

Try it online!

2 bytes thanks to tsh

\$\endgroup\$
  • \$\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 a floor division. Both of wich are more compact expressions. \$\endgroup\$ – Raserhin Dec 6 '19 at 9:04
  • 1
    \$\begingroup\$ a/-b*-b also works, and is slightly more readable, I think? \$\endgroup\$ – Neil Dec 6 '19 at 21:13
  • 1
    \$\begingroup\$ @Neil - Readability?!? Blasphemy! :) \$\endgroup\$ – Chas Brown Dec 6 '19 at 22:59
5
\$\begingroup\$

Haskell, 14 bytes

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

Try it online!

\$\endgroup\$
5
\$\begingroup\$

C++ (gcc), 43 41 40 36 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!!!

\$\endgroup\$
  • \$\begingroup\$ -4 bytes: (b-a%b)%b+a \$\endgroup\$ – Neil Dec 7 '19 at 1:02
  • \$\begingroup\$ @Neil Thanks so much - absolutely brilliant! \$\endgroup\$ – Noodle9 Dec 7 '19 at 1:22
  • \$\begingroup\$ 25 using #macro \$\endgroup\$ – AZTECCO Dec 7 '19 at 12:56
  • \$\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 Dec 7 '19 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 Dec 7 '19 at 14:26
5
\$\begingroup\$

JavaScript (Node.js), 17 bytes

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

Try it online!

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

Jelly, 3 bytes

÷Ċ×

Try it online!

Simply divide, ceiling, multiply.

\$\endgroup\$
4
\$\begingroup\$

C (gcc), 47 31 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

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

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ Welcome to the site! \$\endgroup\$ – Post Rock Garf Hunter Dec 7 '19 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 Dec 8 '19 at 0:25
  • \$\begingroup\$ Okay listen, just 'cause you're right... \$\endgroup\$ – Exalted Toast Dec 8 '19 at 2:45
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

R, 20 bytes

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

K (oK), 8 bytes

{x+y!-x}

Try it online!

Another port of xnor's Python answer.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Ruby, 13 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

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 .

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 10 bytes

≔±NθI×θ÷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.

I×θ÷Nθ

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

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

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
\$\endgroup\$
2
\$\begingroup\$

Javascript (ES6), 19 bytes

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

Naive attempt, pretty sure this can be golfed further.

\$\endgroup\$
2
\$\begingroup\$

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;}
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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).

\$\endgroup\$
2
\$\begingroup\$

Java (JDK), 15 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Pyth, 8 bytes

AQ+G%_GH

Try it online!

Simple port of the Python answer from xnor so please give that answer an upvote.

Debugged:

==================================================
assign('Q',eval_input())
assign('[G,H]',Q)
imp_print(plus(G,mod(neg(G),H)))
==================================================
\$\endgroup\$
  • \$\begingroup\$ -3 with a more direct port \$\endgroup\$ – frank Dec 6 '19 at 19:31
  • 1
    \$\begingroup\$ @frank - Nice. Different enough for you to post as your own if you want to. I'm still a beginner with Pyth. A lot to learn :) \$\endgroup\$ – ElPedro Dec 10 '19 at 19:10
1
\$\begingroup\$

APL+WIN, 8 bytes

Prompts for b followed by a:

b×⌈⎕÷b←⎕

Try it online! Courtesy of Dyalog Classic

\$\endgroup\$

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.