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\$ Commented Jul 21, 2016 at 19:12

117 Answers 117

1 2 3
4
0
\$\begingroup\$

Magma, 13 bytes

IsDivisibleBy 

Pretty readable, I think. Try it at the online calculator, e.g.

IsDivisibleBy(100, 50); IsDivisibleBy(100, 54); 

gives

true false 
\$\endgroup\$
0
\$\begingroup\$

MIXAL, 105 bytes

Not counting bytes for 17 and 8 in the first two lines, which are used for input. Replace with any desired n and d.

Outputs 0 for true and 1 for false.

N EQU 17 D EQU 8 S LDX =N= DIV =D= ENTA 30 JXZ T INCA 1 T STA 9 OUT 9(19) HLT END S 

Commented version:

N EQU 17 Constants used for input D EQU 8 START LDX =N= Put value 'n' into rX DIV =D= Divide rAX by value 'd'; rA <= quotient; rX <= remainder ENTA 30 Replace rA value with character code for '0' JXZ T If rX == 0, then d is a divisor of n, go to 'T' INCA 1 Else (there is a remainder), add 1 to rA charcode for '1' T STA 9 Store rA charcode at address 9 (after end of program) OUT 9(19) Send contents starting at address 9 to TTY output device HLT END START 
\$\endgroup\$
0
\$\begingroup\$

RProgN, 3 Bytes

% ! 

Explination

% # Take the Modulus of the value under the top of the stack compared to the top of the stack. (The Inputs in order, conveniently enough) ! # Push the Boolean not of it. In this case, 0 is falsey, and all numbers !=0 are truthy, so false correctly inverts it. 

Yay, RProgN is a competitive language!

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

PHP, 53 Bytes

Trying to get the boutny for an exemplary answer

$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==end($r); 

My answer based on Set Theory In the set from d to n where all items are multiple from d if n is the last member of the set it is divisible by d

Expressed differently you could say that the count of the items multiplied with d must be n

$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==count($r)*$d; 
\$\endgroup\$
0
\$\begingroup\$

Racket 26 bytes

(λ(n m)(= 0(modulo n m))) 

Usage:

(define f (λ(n m) (= 0 (modulo n m)))) 

Testing:

(f 1 1) (f 2 1) (f 6 3) (f 17 17) (f 22 2) (f 1 2) (f 2 3) (f 2 4) (f 3 9) (f 15 16) 

Output:

#t #t #t #t #t #f #f #f #f #f 
\$\endgroup\$
0
\$\begingroup\$

tinylisp (REPL), 38 bytes

(d |(q((N D)(i(l N D)(e N 0)(|(s N D)D 

Defines a function | that takes N and D and returns 1 if divisible, 0 otherwise. The REPL infers closing parentheses as necessary at the end of the code. Call the function like (| 22 2).

Ungolfed/explanation:

(d | Define | to be... (q ( a function, i.e. a list containing... (N D) list of params N and D, and function body: (i (l N D) If N is less than D, then return: (e N 0) 1 if N equals 0, 0 otherwise; (| (s N D) D))))) Else, recurse with arguments N - D and D 

Gets kinda slow for N around D * 10^5 and larger.

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

TI-Basic, 10 bytes

Prompt N,D:not(fPart(N,D 

Returns 1 for true or 0 for false

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

GameMaker Language, 32 bytes

return 1>argument0 mod argument1 
\$\endgroup\$
0
\$\begingroup\$

bc, 19 bytes

!read()%read() quit 

The positive integers n and d are read from STDIN in that order, separated by any whitespace. The script prints 1 if n is evenly divisible by d, or 0 otherwise.

Run examples:

me@LCARS:/PPCG$ bc --quiet divisibility_test.bc 12 4 1 me@LCARS:/PPCG$ bc --quiet divisibility_test.bc 12 5 0 
\$\endgroup\$
0
\$\begingroup\$

AWK, 14 bytes

{$0=!($1%$2)}1 

Usage:

awk '{$0=!($1%$2)}1' <<< "N D" 

Output will be 1 for true and 0 for false. N and D can be integers or floating point numbers.

\$\endgroup\$
1
  • \$\begingroup\$ 11 bytes ``` $0=!($1%$2) ``` Attempt This Online! Prints 1 for true, or nothing for false. #### 13 bytes ``` 1,$0=!($1%$2) ``` 1 for true, 0 for false. \$\endgroup\$ Commented Mar 15 at 1:38
0
\$\begingroup\$

QBIC (Non-competing), 8 bytes

::?a%b=0 

For this challenge, I've improved QBIC's user input of numeric values. : now takes a command line argument and casts this to num.

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

Excel VBA, 14 Bytes

Anonymous VBE immediates window function that takes input of expected type variant\integer from cells [A1] and [A2] and outputs as a boolean variable to the VBE immedates window

?[A1]mod[A2]=0 
\$\endgroup\$
0
\$\begingroup\$

REXX, 18 bytes

arg n d say n//d=0 
\$\endgroup\$
0
\$\begingroup\$

Functoid, 21 bytes

Y(yg(KZ)(BBC+C-))$$;@ 

Full program expecting two arguments d and n, try it online!

Explanation

Y( ) # fix point of the following function y # define recursive function with 2 arguments g # - base case: x > y (KZ) # - in base case: check y == 0 (BBC+C-) # - else: call f recursively with x and (y-x) $$ # apply two command-line arguments ; # print as a boolean @ # terminate program 
\$\endgroup\$
0
\$\begingroup\$

T-SQL, 27 bytes

Per our input standards, input is provided via pre-existing table t, with integer fields n and d:

SELECT IIF(n%d=0,1,0)FROM t 

'%' is the remainder/modulo operator in SQL.

Note that the original list of test values could be improved: the 5 failing cases all fail trivially because n < d. Some better test values (5 succeeding, 5 failing):

(200,50),(91,7),(999,3),(45,5),(10000,2),(45,10),(99,2),(100,98),(100,24),(100,51)

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

Japt, 2 bytes

vV 

Returns 1 for true, 0 for false.

Try it online!

Test cases

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

Common Lisp, 27 Bytes

(lambda(n d)(= 0(mod n d))) 

Pretty basic.

Explanation:

(lambda(n d)( )) | Function of two arguments = 0(mod n d) | Test if n mod d == 0 
\$\endgroup\$
0
\$\begingroup\$

W , 3 bytes

Sm! 

Explanation

Sm! 

With implicit input:

baSm! 
baS % Produce a,b m % Produce a%b ! % Negate the value 
\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 1 byte

Attempt This Online!

Built-in.

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

Rockstar, 58 bytes

listen to N listen to D let M be N/D turn M up say M's N/D 

Try it (Code will need to be pasted in)

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

Pascal, 54 B

d divides n if division with remainder (Pascal’s div and mod operators) yields no remainder (the result of the mod operation), i. e. a value of zero.

function f(n,d:integer):Boolean;begin f:=n mod d=0 end 

The second (right‑hand) operand to mod must be positive. The value of n mod d is n − (kd) where k is an integer so that n mod d ≥ 0 and n mod d < d.

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

Swift, 15 bytes

let f={$0%$1<1} 

Self-explanatory.

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

Ruby, 12 bytes

I was surprised there's no Ruby solution yet. Ergo:

->n,d{n%d<1} 

Attempt This Online!

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

J-uby, 7 bytes

:%|:>&1 

Attempt This Online!

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

Tcl, 26 bytes

proc D n\ d {expr $n%$d<1} 

Try it online!

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

C#

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication181 { class Program { static void Main(string[] args) { Console.WriteLine("Enter the Maximum Range of the Array:"); int N = Convert.ToInt32(Console.ReadLine()); int[] div = new int[N]; int[] num = new int[N]; int[] quo = new int[N]; int d = 0, n = 0, q = 0; Console.WriteLine("\n"); Console.WriteLine("Enter the numbers:"); for (n = 0; n < N; n++) { num[n] = Convert.ToInt32(Console.ReadLine()); } Console.WriteLine("\n"); Console.WriteLine("Enter the Divident values:"); for (d = 0; d < N; d++) { div[d] = Convert.ToInt32(Console.ReadLine()); } Console.WriteLine("\n"); for (d = 0; d < N; d++) { for (n = 0; n < N; n++) { if (d == n) { quo[q] = (num[n] / div[d]); q++; } } } Console.WriteLine("\n"); Console.WriteLine("The Quotient values are:"); for (q = 0; q < N; q++) { Console.Write("{0} ", quo[q]); } Console.WriteLine("\n"); Console.WriteLine("d n output"); for (d = 0; d < N; d++) { for (n = 0; n < N; n++) { for (q = 0; q < N; q++) { if ((d == n)&&(n == q)&&(q==d)) { if ((quo[d] * div[d]) == num[n]) { Console.WriteLine("{0} {1} truthy", div[d], num[n]); } else { Console.WriteLine("{0} {1} False ",div[d],num[n]); } } } } } Console.WriteLine("\n"); Console.ReadLine(); } } } 
\$\endgroup\$
2
  • 4
    \$\begingroup\$ This is a code golf challenge you know? Where you're trying to get the lowest amount of bytes possible? \$\endgroup\$ Commented Oct 12, 2016 at 11:41
  • 3
    \$\begingroup\$ Answers must attempt to lower their byte count to be considered a serious answer for code-golf. Essentially, make your code as small as possible, while still having it be able to run. \$\endgroup\$ Commented Oct 12, 2016 at 13:31
-2
\$\begingroup\$

TCC, 1 byte

v 

Input is 2 numbers seperated by a space

Try it online!

\$\endgroup\$
0
1 2 3
4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.