43
\$\begingroup\$

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in bytes – wins.

Test cases

 n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog 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 + 3 (-p flag) = 45 bytes

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

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

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><script>var QUESTION_ID = 86149; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; 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.toLowerCase(), 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 > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) 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); } }</script>

\$\endgroup\$
1
  • \$\begingroup\$ This conversation has been moved to chat. \$\endgroup\$
    – Dennis
    Commented Jul 21, 2016 at 19:12

116 Answers 116

3
\$\begingroup\$

Forth (gforth), 13 12 bytes

: x mod 0= ;

:   - create new word
x   - word name
mod - modulus operator
0=  - compare value on stack with 0
;   - end word

Use like n d x .

Test cases (-1 is true, 0 is false) :

1 1 x . -1  ok
2 1 x . -1  ok
6 3 x . -1  ok
17 17 x . -1  ok
22 2 x . -1  ok
1 2 x . 0  ok
2 3 x . 0  ok
2 4 x . 0  ok
3 9 x . 0  ok
15 16 x . 0  ok

My first submission! :D

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

ArnoldC, 244 bytes

HEY CHRISTMAS TREE r
YOU SET US UP 0
GET TO THE CHOPPER r
HERE IS MY INVITATION a
I LET HIM GO b
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE r
TALK TO THE HAND 0
BULLSHIT
TALK TO THE HAND 1
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

Try it online!

How it works

HEY CHRISTMAS TREE r               // Define Variable r
YOU SET US UP 0                    // Set r to 0 

GET TO THE CHOPPER r               // Start declaration of r 
HERE IS MY INVITATION a            // Use a for calculation
I LET HIM GO b                     // set r to a mod b
ENOUGH TALK                        // End declaration of r

BECAUSE I'M GOING TO SAY PLEASE r  // if r > 0
TALK TO THE HAND 0                 // print 0
BULLSHIT                           // else
TALK TO THE HAND 1                 // print 1
YOU HAVE NO RESPECT FOR LOGIC      // end if

YOU HAVE BEEN TERMINATED           //end main
\$\endgroup\$
3
\$\begingroup\$

Pyth, 6 4 3 bytes

%.*

Try It Online!

Input is passed as an array [n,d]. Output is zero for false and a positive integer for true.

Explanation follows:

 .*   Unwraps input (from [n,d] to n, d)
%     Takes n (mod d).
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Steadybox
    Commented Jan 12, 2018 at 23:02
2
\$\begingroup\$

Pyke, 2 bytes

%!

Try it here!

not (a mod b)
\$\endgroup\$
0
2
\$\begingroup\$

MATL, 2 bytes

\~

Try it online!

\    % Take two inputs implicitly. Compute their modulo
~    % Logical negate. Implicit display
\$\endgroup\$
2
\$\begingroup\$

Befunge, 6 bytes

&&%!.@

Try it here! Input two numbers, separated by a space. Output is 0 or 1 for falsy or truthy.

\$\endgroup\$
1
  • \$\begingroup\$ &<@.!% also works \$\endgroup\$ Commented Feb 14, 2017 at 23:05
2
\$\begingroup\$

Actually, 3 2 bytes

%Y

Saved one byte thanks to @Mego.

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ %Y is shorter \$\endgroup\$
    – user45941
    Commented Jul 21, 2016 at 23:19
2
\$\begingroup\$

Excel VBA, 62 bytes

Function q(b, c)
If b / c = Int(b / c) Then q = 1
End Function
\$\endgroup\$
2
\$\begingroup\$

VBA, 46 44 41 bytes

Function f(i,j)
f=i Mod j = 0
End Function
\$\endgroup\$
2
  • \$\begingroup\$ Thanks again. I also made a personal favorite f=InStr(i/j,".")=0. Doesn't work with decimal commas and isn't winning bytes. \$\endgroup\$ Commented Jul 22, 2016 at 12:47
  • \$\begingroup\$ Personal preference; when I'm testing values with Mod, I put the test constant first: 0=i Mod j And if you append the body line onto the function declaration, , you'll actually get the End Function line for the price of pressing Enter: Function f(i,j):f=0=i Mod j (28 bytes) \$\endgroup\$
    – Joffan
    Commented Jul 23, 2016 at 18:34
2
\$\begingroup\$

JavaScript (ES6), 12 Bytes

EDIT

This post was beaten here


d=>h=>d%h==0

Explanation:

d=>
   h=>
    d%h==0 // Is the remainder of d/h equal to 0 (i.e. is it divisible)
\$\endgroup\$
2
  • \$\begingroup\$ How is it different from this? \$\endgroup\$
    – Leaky Nun
    Commented Jul 22, 2016 at 12:34
  • \$\begingroup\$ Sorry, I only checked the first page for answers! Didn't even know that existed. I'll delete it now. \$\endgroup\$
    – bren
    Commented Jul 22, 2016 at 15:59
2
\$\begingroup\$

Bash, 23 bytes

expr `expr $N % $D` % 2

I'm sure it can be even shorter...

Output is 0 if N is divisible by D, 1 if it is not

\$\endgroup\$
5
  • 3
    \$\begingroup\$ Truthy and falsy don't mean literally the strings "truthy and "falsy", just whatever the natural true/false values are for the language. In the case of bash I'd say an exit code of 0 for truthy and an exit code of 1 for falsy would be appropriate here. \$\endgroup\$ Commented Jul 22, 2016 at 16:09
  • \$\begingroup\$ How does % 2 give 1 for 0 and 0 for everything else? \$\endgroup\$
    – Titus
    Commented Jul 22, 2016 at 18:02
  • \$\begingroup\$ @Titus % 2 means modulo 2. It divides $N by $D, then returns the remainder \$\endgroup\$ Commented Jul 23, 2016 at 14:18
  • \$\begingroup\$ I know % ... but %2 will give you 0 for 0 and for every other even remainder, 1 for odd remainders, i.e. a falsy value (0) for remainder 0 (which should have a truthy result) and a truthy one (1) for half of the possible remainders (that should all return a falsy value). \$\endgroup\$
    – Titus
    Commented Jul 23, 2016 at 15:05
  • \$\begingroup\$ This answer is incorrect. It gives 0 (divisible) for N=2 and D=4 for example. \$\endgroup\$
    – seshoumara
    Commented Oct 11, 2016 at 9:37
2
\$\begingroup\$

Jellyfish, 5 bytes

pN/|i

Input is a list containing [d n].

Try it online!

The i is replaced with the input value when the program starts. /| folds modulo over the list, taking the second list element modulo the first. N is logical negation, giving 1 for input 0 and 0 for everything else.

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

R, 20 bytes

Small improvement on this answer.

a=scan();!a[1]%%a[2]

If the result of the modulo operation is 0, this is interpreted as a false, which is then inverted by the !. Any other number would be a truthy, which again is inverted by the ! into a false.

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

Forth, 6 bytes

mod 0=

example usage

10 2 mod 0=

This is the same code given by @therealfarfetchd, but without the definition (almost all other entries are not given in definition format)

\$\endgroup\$
7
  • \$\begingroup\$ Is this actually a full program then? All answers are required to be either full programs or callable functions, not just snippets. \$\endgroup\$ Commented Oct 11, 2016 at 17:48
  • \$\begingroup\$ @MartinEnder When I answer in Forth, I always use a function (word) declaration, because the standard method of taking input is having it already on the stack, and returning is leaving it on the stack or printing. Idk if there is a difference between a full program and a snippet, so I've always considered it a snippet. \$\endgroup\$
    – mbomb007
    Commented Oct 11, 2016 at 18:07
  • \$\begingroup\$ @MartinEnder check short answers above, (i.e. Befunge, Tcl, J, PowerShell, Jellyfish, Pyth, Minkolang, Perl 5, 05AB1E, R ... etc). \$\endgroup\$ Commented Oct 13, 2016 at 14:33
  • \$\begingroup\$ @Ala'aMohammad I don't know Tcl but Befunge, Powershell, Jellyfish, Pyth, Minkolang, 05AB1E, R are all full programs. Perl and J are callable functions. \$\endgroup\$ Commented Oct 13, 2016 at 14:37
  • \$\begingroup\$ @MartinEnder for example in 'J' shouldn't functions(verbs) start at least with assignment '=:'? (which is not used in J here) \$\endgroup\$ Commented Oct 14, 2016 at 20:43
2
\$\begingroup\$

C, 20 19 bytes

#define f(a,b)a%b<1

Defines a macro f(a,b), which gets preprocessed to !(a%b). I assure you you don't need parens here, because it's just a unary operator. Anyways, if you're a purist, then this will do it, at 25 bytes:

#define f(a,b)((a)%(b)<1)

For a real function, go check Albert's answer :)

\$\endgroup\$
2
  • \$\begingroup\$ +1 This is very clever I've never seen a pre-processor answer before but it saves so much hassle of using return and {, }, ; which are always killers for C on codegolf! \$\endgroup\$ Commented Feb 15, 2017 at 3:00
  • \$\begingroup\$ Think I got you beat at 16 bytes though 😏 codegolf.stackexchange.com/a/110084/16513 \$\endgroup\$ Commented Feb 15, 2017 at 3:11
2
\$\begingroup\$

Chip, 356 bytes

*Z~v---v---v---v---v---v---v---.
e H/vZG/vZF/vZE/vZD/vZC/vZB/vZA/vZ
 f*z|)--x)--x)--x)--x)--x)--x)--x)~a
A~#Mxx--xx--xx--xx--xx--xx--xx--xx.
B~#Mxx--xx--xx--xx--xx--xx--xx. `@'
C~#Mxx--xx--xx--xx--xx--xx. `@@--'
D~#Mxx--xx--xx--xx--xx. `@@--('
E~#Mxx--xx--xx--xx. `@@--('
F~#Mxx--xx--xx. `@@--('
G~#Mxx--xx. `@@--('
H~#Mxx. `@@--('
 t~Z`@@--('
,^-{-('
`~Ss

Try it online!

The basic strategy here is to repeatedly subtract the divisor from the dividend until we hit zero, or we go negative. Since Chip only has adders, we negate the divisor and repeatedly add instead, looking for the first iteration that doesn't result in an overflow. Chip operates on eight bits at a time, so this solution only handles positive, signed, two's complement, one-byte integers; therefore input values are allowed to range from 1 to 127. Zero values are somewhat handled: 0/n and 0/0 are truthy; n/0 is falsy.

Each input value is read as a byte, which is why the TIO uses a bit of awk. The inputs saved in the TIO link are the test case 22/2==truthy.

Output is given as ASCII '0' or '1', because it required no extra bytes over code points 0x0 and 0x1.

How it works

This is rather complex (as you may have noticed), so I'll just cover the highlights.

On the first cycle, the dividend, n, is read in via the elements A through H in line 2, and stored for the next cycle in the Z elements to their right.

On the second tick, the divisor, d, is read in via A through H in the first column of lines 4 and onward. This is immediately bitwise-negated via the ~'s and incremented by one via the #'s. We can now store the inverse value, -d, in the column of M elements.

Starting on the second cycle, and every cycle thereafter, n is incremented by -d in the diagonal grouping of @ elements (each pair corresponds to a full-adder), and the new value is stored back in the Z's above.

If there is no overflow carry on the operation, the block with t, S, and s in the lower left will print out one byte and terminate execution. The a at top right will determine whether a '1' or a '0' is printed, based on whether n is currently zero or not.

The other Z and z elements are to provide initialization values for the first cycle, since we don't have d yet. The elements e and f in the top left perform the mapping to ASCII for output. Pretty much all the other elements are wires, to connect everything up.

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

C, 16 bytes

Believe it or not C (GCC) will return the last modified value if no return method is called.

That said,

f(a,b){a=a%b<1;}

Try it online


Special thanks to @Ahemone and @l4m2 for teaching me about this trick today

\$\endgroup\$
2
  • 1
    \$\begingroup\$ It's not first argument, but last modified value \$\endgroup\$
    – l4m2
    Commented Mar 23, 2018 at 6:39
  • \$\begingroup\$ @l4m2 I was wondering how correct that was, thank you; editing it in! \$\endgroup\$ Commented Mar 23, 2018 at 6:47
2
\$\begingroup\$

ECMAScript Regex, 10 bytes

^(x+),\1*$

Try it online!

Deciding to learn this after seeing some of Deadcode's amazing submissions. Clearly, I'm starting off with much easier problems. Takes input as d,n, with both number in unary, and matches if the n is divisible by d.

Explanation:

^           From the start of the string
 (x+)       Capture d xs in \1
     ,      Match the separator
      \1*^  In n, match d repeatedly until the end of the string
\$\endgroup\$
2
\$\begingroup\$

Pyt, 1 byte

|

Try it online!

Trivial built-in. Takes d then n

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

Pyth, 3 bytes

!%F

Test suite.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Alternatively: }iF \$\endgroup\$ Commented Jul 21, 2016 at 16:21
1
\$\begingroup\$

Minkolang 0.15, 6 bytes

nn%,N.

Try it here!

Explanation

nn        Take two numbers from input
  %       Pop b, a and push a%b
   ,      NOT top of stack
    N.    Output as number and stop.
\$\endgroup\$
1
\$\begingroup\$

Clojure, 64 bytes

(fn[n d](nil?(some #((set %) \a)(partition d d "a" (range n)))))

Not a competitive solution but does not use any arithmetic operations. Partitions range 0 .. n into lists of length d and if there is not enough elements for the last list adds "a"s to it. And then try to find a list which contains \a character.

See it online: https://ideone.com/prK5Iq

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

Perl 5, 14 bytes

A subroutine:

{!((pop)%pop)}

See it in action thus:

perl -E"say sub{!((pop)%pop)}->(3,17)"

First argument is d, second is n.

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

F#, 18 bytes

let d a=(%)a>>(=)0

Usage:

d 6 3;;
> val it : bool = true

I can shave 1 byte if I define a lambda instead but then I can't use it later.

fun a->(%)a>>(=)0
\$\endgroup\$
1
\$\begingroup\$

C++, 36 bytes

bool d(int n, int d){return n%d==0;}

Explanation:

bool isDivisible(int dividend, int divisor) {
    return n % d == 0; // the modulo operator returns remainder,
    // if the number evenly divides, there will be no remainder
}

Usage:

#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
    int div = std::stoi(argv[1]);
    int divis = std::stoi(argv[2]);
    if (isDivisible(div, divis)) {
        std::cout << "They're evenly divisible!" << std::endl;
    } else {
        std::cout << "They're not evenly divisible." << std::endl;
    }
    return 0;
}
\$\endgroup\$
1
  • \$\begingroup\$ Nice! Try this, though. It uses a int to take off 1 byte, uses the less than operator to take off another, and removes a whitespace. int d(int n,int d){return n%d<1;} \$\endgroup\$
    – Jeremy
    Commented Jul 22, 2016 at 12:58
1
\$\begingroup\$

C, 33 bytes

int k(int n,int d){return 1>n%d;}

Returns a non-zero integer if the number n is divisible by d, zero otherwise.

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

Racket, 26 bytes

(λ(n m)(integer?(/ n m)))
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 6 bytes

II%0Q,

Uses CP-1252 encoding. Try it online!

You can also use the built in

Ö

which does exactly what the challenge asks. Just that the 2 inputs are swapped. Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Very nice! You can also use the built-in Ö which does exactly what the challenge asks. You only need to specify that the 2 inputs are swapped. \$\endgroup\$
    – Adnan
    Commented Jul 21, 2016 at 22:29
  • \$\begingroup\$ IIrÖ solves that problem, doesn't it? \$\endgroup\$ Commented Oct 7, 2016 at 18:14
1
\$\begingroup\$

C++11, 31 bytes

[](int n,int d){return n%d<1;}

Uses the fact that a%b is always non-negative for positive numbers, and therefore only n%d==0 fulfills n%d<1.

Usage:

int main(){
   const auto lambda = [](int n,int d){return n%d<1;};
   std::cout << lambda(100,2) << "\n";
             << lambda(100,3) << std::endl;
}

Result:

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

Element, 7 bytes

__%?!"`

Wow, I'm even more disappointed than expected. It takes two numbers as input, performs the modulo operation, tests for truthiness, negates the result (so a modulo of 0 is converted to a "true" and other numbers are "false"), then moves this result to the main stack, and then outputs it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.