Divisibility test

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


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.

## 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>

• This conversation has been moved to chat. – Dennis Jul 21 '16 at 19:12

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

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

• +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! – Albert Renshaw Feb 15 '17 at 3:00
• Think I got you beat at 16 bytes though 😏 codegolf.stackexchange.com/a/110084/16513 – Albert Renshaw Feb 15 '17 at 3:11

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

• Welcome to PPCG! – Steadybox Jan 12 '18 at 23:02

Pyke, 2 bytes

%!


Try it here!

not (a mod b)


MATL, 2 bytes

\~


Try it online!

\    % Take two inputs implicitly. Compute their modulo
~    % Logical negate. Implicit display


Befunge, 6 bytes

&&%!.@


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

Actually, 3 2 bytes

%Y


Saved one byte thanks to @Mego.

Try it online!

Excel VBA, 62 bytes

Function q(b, c)
If b / c = Int(b / c) Then q = 1
End Function


VBA, 4644 41 bytes

Function f(i,j)
f=i Mod j = 0
End Function

• Yes, thank you! – user3819867 Jul 22 '16 at 12:28
• Thanks again. I also made a personal favorite f=InStr(i/j,".")=0. Doesn't work with decimal commas and isn't winning bytes. – user3819867 Jul 22 '16 at 12:47
• 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) – Joffan Jul 23 '16 at 18:34

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)

• How is it different from this? – Leaky Nun Jul 22 '16 at 12:34
• Sorry, I only checked the first page for answers! Didn't even know that existed. I'll delete it now. – MayorMonty Jul 22 '16 at 15:59

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

• 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. – a spaghetto Jul 22 '16 at 16:09
• How does % 2 give 1 for 0 and 0 for everything else? – Titus Jul 22 '16 at 18:02
• @Titus % 2 means modulo 2. It divides $N by $D, then returns the remainder – Universal Electricity Jul 23 '16 at 14:18
• 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). – Titus Jul 23 '16 at 15:05
• This answer is incorrect. It gives 0 (divisible) for N=2 and D=4 for example. – seshoumara Oct 11 '16 at 9:37

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.

R, 20 bytes

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.

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)

• Is this actually a full program then? All answers are required to be either full programs or callable functions, not just snippets. – Martin Ender Oct 11 '16 at 17:48
• @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. – mbomb007 Oct 11 '16 at 18:07
• @MartinEnder check short answers above, (i.e. Befunge, Tcl, J, PowerShell, Jellyfish, Pyth, Minkolang, Perl 5, 05AB1E, R ... etc). – Ala'a Mohammad Oct 13 '16 at 14:33
• @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. – Martin Ender Oct 13 '16 at 14:37
• @MartinEnder for example in 'J' shouldn't functions(verbs) start at least with assignment '=:'? (which is not used in J here) – Ala'a Mohammad Oct 14 '16 at 20:43

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


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.

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

• It's not first argument, but last modified value – l4m2 Mar 23 '18 at 6:39
• @l4m2 I was wondering how correct that was, thank you; editing it in! – Albert Renshaw Mar 23 '18 at 6:47

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


Pyth, 3 bytes

!%F

• Alternatively: }iF – FryAmTheEggman Jul 21 '16 at 16:21

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.


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

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.

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


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;
}

• 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;} – Jeremy Jul 22 '16 at 12:58

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.

Racket, 26 bytes

(λ(n m)(integer?(/ n m)))


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!

• 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. – Adnan Jul 21 '16 at 22:29
• IIrÖ solves that problem, doesn't it? – Magic Octopus Urn Oct 7 '16 at 18:14

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


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.

Excel, 31 13 bytes

=0=MOD(A1,A2)


Enter n in A1, d in A2.

For some reason I convinced myself that we had to handle all integers, so I had =IFERROR(A1/A2=INT(A1/A2),A1=0) to handle d=0.