| Bytes | Lang | Time | Link |
|---|---|---|---|
| 026 | Tcl | 250507T083321Z | sergiol |
| 033 | Go | 230325T203901Z | The Thon |
| 007 | Juby | 240312T190514Z | Jordan |
| 012 | Ruby | 240312T190354Z | Jordan |
| 015 | Swift | 240312T183149Z | macOSist |
| 054 | Pascal | 240312T180011Z | Kai Burg |
| nan | Piet + asciipiet | 220702T005832Z | naffetS |
| 058 | Rockstar | 230607T152421Z | Shaggy |
| 001 | Thunno 2 | 230607T071659Z | The Thon |
| 004 | Raku | 161004T043029Z | elcaro |
| 029 | Scratch | 230326T135001Z | The Thon |
| 002 | Thunno | 230326T071748Z | The Thon |
| 007 | Trilangle | 230326T013721Z | Bbrk24 |
| 001 | Pyt | 230325T213354Z | Kip the |
| 019 | Desmos | 230325T204756Z | Youserna |
| 003 | APL Dyalog Unicode | 160721T161545Z | Adá |
| 001 | Vyxal | 220611T180657Z | naffetS |
| 008 | Factor | 220611T073549Z | chunes |
| 001 | TCC | 160726T152048Z | brianush |
| 002 | Keg | 190915T233518Z | user8505 |
| 003 | W | 200102T132132Z | user8505 |
| 010 | ECMAScript Regex | 190123T122309Z | Jo King |
| 016 | C | 170215T031040Z | Albert R |
| 356 | Chip | 170214T224854Z | Phlarx |
| 003 | Pyth | 180112T224858Z | ericesch |
| 027 | Common Lisp | 180113T201329Z | Bolce Bu |
| 002 | Japt | 180112T230755Z | Oliver |
| 027 | TSQL | 180112T230504Z | BradC |
| 021 | Functoid | 180112T222548Z | ბიმო |
| 018 | REXX | 170329T115903Z | idrougge |
| 244 | ArnoldC | 170329T112935Z | Tom291 |
| 014 | Excel VBA | 170325T194645Z | Taylor R |
| 011 | Java 8 | 160722T184300Z | David Co |
| nan | 160722T180110Z | Erik the | |
| 008 | QBIC Noncompeting | 160723T081124Z | steenber |
| 086 | BrainFlak | 160725T201428Z | Wheat Wi |
| 003 | ASMD | 161121T215031Z | Oliver N |
| 012 | Groovy | 161121T212420Z | Rado |
| 024 | Python 2 | 161120T184811Z | AvahW |
| 046 | BrainFlak | 161003T053010Z | Dennis |
| 006 | Forth | 161011T174201Z | Ala' |
| 014 | Elixir | 161012T160330Z | adrianmp |
| nan | 161012T112501Z | Thiru Ar | |
| 013 | Bash | 161011T110620Z | seshouma |
| 001 | 05AB1E | 161007T165024Z | Geno Rac |
| 016 | Emotinomicon | 161005T092221Z | Linnea G |
| 014 | AWK | 161011T132523Z | Robert B |
| 019 | bc | 161011T113952Z | seshouma |
| 020 | R | 160722T070345Z | Andre |
| 032 | GameMaker Language | 161006T152559Z | Timtech |
| 010 | TIBasic | 161006T152337Z | Timtech |
| 020 | R | 161006T091035Z | JAD |
| 038 | tinylisp REPL | 161004T055944Z | DLosc |
| 001 | Vitsy | 161005T163502Z | Addison |
| 026 | Racket | 161005T041947Z | rnso |
| 262 | Logicode | 161003T061541Z | clismiqu |
| 053 | PHP | 161004T195738Z | Jör |
| 003 | RProgN | 161003T224549Z | ATaco |
| 011 | Javascript ES6 | 160721T163628Z | user5418 |
| 105 | MIXAL | 161003T203725Z | musarith |
| 012 | Forth gforth | 160724T195610Z | 2xsaiko |
| 096 | Brainflak | 160721T163052Z | DJMcMayh |
| 005 | Jellyfish | 160807T094318Z | Martin E |
| 1311 | Haskell | 160722T055829Z | Zeta |
| 020 | PowerShell v2+ | 160721T192008Z | AdmBorkB |
| 013 | Magma | 160725T103818Z | Sp3000 |
| 008 | x86_32 machine code | 160723T070649Z | davey |
| 003 | ><> | 160724T142731Z | SE - sto |
| 015 | 3d | 160723T175902Z | joH1 |
| 013 | Java | 160723T163132Z | user8397 |
| 010 | Hexagony | 160722T014218Z | Blue |
| 009 | q | 160723T103442Z | skeevey |
| 008 | Labyrinth | 160721T201817Z | Martin E |
| 003 | Mathematica | 160721T221824Z | Yytsi |
| 027 | Batch | 160723T055322Z | sudoBash |
| 024 | ROOP | 160723T050105Z | DarkPhan |
| 016 | Sesos | 160723T033449Z | Leaky Nu |
| 007 | dc | 160723T002709Z | juh |
| 001 | Jelly | 160721T161502Z | DJMcMayh |
| 015 | Clojure | 160722T203054Z | MattPutn |
| 012 | C# | 160721T231754Z | user1954 |
| 003 | J | 160722T192554Z | emiflake |
| 013 | Excel | 160721T222307Z | Joffan |
| 022 | PHP | 160722T130953Z | Titus |
| 060 | C | 160721T214759Z | Ronronne |
| 034 | Tcl | 160721T162736Z | user5567 |
| 107 | MarioLANG | 160722T153139Z | Business |
| 023 | Bash | 160722T155518Z | Universa |
| 7464 | LOLCODE | 160722T154543Z | AAM111 |
| 012 | JavaScript ES6 | 160722T060733Z | bren |
| 007 | Element | 160722T155140Z | PhiNotPi |
| 041 | VBA | 160722T122556Z | user3819 |
| 062 | Excel VBA | 160722T115002Z | tjb1 |
| 031 | C++11 | 160722T111737Z | Zeta |
| 002 | Actually | 160721T165856Z | user4853 |
| 006 | 05AB1E | 160721T164744Z | user4853 |
| 026 | Racket | 160722T070021Z | Winny |
| 033 | C | 160722T060640Z | Zeta |
| 036 | C++ | 160722T012240Z | Initiali |
| 018 | F# | 160722T003406Z | asibahi |
| 006 | Befunge | 160721T221659Z | user5585 |
| 002 | MATL | 160721T211141Z | Luis Men |
| 053 | brainfuck | 160721T205430Z | mbomb007 |
| 014 | Perl 5 | 160721T201333Z | msh210 |
| 011 | Vim | 160721T201105Z | DJMcMayh |
| 064 | Clojure | 160721T192856Z | cliffroo |
| 078 | Fortran 95 | 160721T164659Z | Jeremy |
| 006 | Minkolang 0.15 | 160721T185202Z | El'e |
| 009 | Julia | 160721T170614Z | Dennis |
| 020 | Batch | 160721T165843Z | Neil |
| 012 | Retina | 160721T164802Z | lynn |
| 002 | Brachylog | 160721T165141Z | Fatalize |
| 004 | CJam | 160721T162747Z | Business |
| 003 | GolfScript | 160721T163430Z | xenia |
| 002 | Pyke | 160721T161439Z | Blue |
| 016 | Python | 160721T161957Z | Dennis |
| 003 | Pyth | 160721T161217Z | Leaky Nu |
Go, 37 33 bytes
func f(n,d int)bool{return n%d<1}
Simple solution but requires a pretty big boilerplate around it.
-4 thanks to @Divy
Swift, 15 bytes
let f={$0%$1<1}
Self-explanatory.
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.
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)
Raku, 4 bytes
*%%*
Anonymous function that takes 2 arguments, here represented with *, using the infix "is divisable by" operator %%, which returns a Bool value
Scratch, 31 29 bytes
define(n)(d
say<(0)=((n)mod(d
-2 thanks to @lyxal
This is my first time golfing in Scratch, so if I've scored it wrong, let me know.
Thunno, 2 bytes
(Actually \$ 2\log_{256}(96)\approx \$ 1.65 bytes but the leaderboard doesn't take decimals)
$!
Takes \$n\$ then \$d\$.
$ is swapped modulo, and ! is logical not.
Trilangle, 7 bytes
??~%!@(
Try it on the online interpreter!
Outputs '0' for true and a negative number for false, in accordance with how the language's branching constructs work.
In C-family syntax, this would be:
print(-(input() % input()));
The choice to treat negative numbers as falsey is arbitrary, but consistent with my answers to other questions. If negative numbers are instead truthy (with positive numbers and zero being falsey), this could be done in just six bytes:
??(%!@
i.e:
print(input() % input() - 1);
Keg, 2 bytes
%;
Takes 2 integers, modulos them. A zero value is falsy, and a non-zero value is truthy; therefor the decrement instruction ; reverses those values.
W , 3 bytes
Sm!
Explanation
Sm!
With implicit input:
baSm!
baS % Produce a,b
m % Produce a%b
! % Negate the value
ECMAScript Regex, 10 bytes
^(x+),\1*$
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
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;}
Special thanks to @Ahemone and @l4m2 for teaching me about this trick today
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
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.
Pyth, 6 4 3 bytes
%.*
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).
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
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)
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
REXX, 18 bytes
arg n d
say n//d=0
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
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
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
Java 8, 11 bytes
a->b->a%b<1
What the heck, there are JS and C# versions of this, why not a Java version, too?
Usage:
import java.util.function.Function;
public class Program {
public static void main(String[] args) {
System.out.printf("%d, %d %b%n", 9, 3, divides(9, 3, a->b->a%b<1));
System.out.printf("%d, %d %b%n", 3, 9, divides(3, 9, a->b->a%b<1));
}
public static boolean divides(int a, int b,
Function<Integer, Function<Integer, Boolean>> f) {
return f.apply(a).apply(b);
}
}
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 :)
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.
Brain-Flak, 88 86 bytes
(<({}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}<>(({}<{}>)){{}{}(<(())>)}{}
This is a denser version of the original Brain-Flak divisibility test algorithm written by Dr Green Eggs and Iron Man DJMcMayhem and myself.
Here is a brief(ish) explanation of how it works:
({}<>) #Move the top of the stack to the other stack #Start Mod
(< >) #Push zero
<> #Switch stacks
{ #While the top of the stack is not zero
({}[()]) #Subtract one from the top of the stack
<> #Switch stacks
{}() #Pop the top, add one and ...
[({})] #Subtract the second element on the stack
(( )) #Push twice
{ #If the top is not zero
{} #Pop the duplicate
({}({})) #Add the second element to the first
(< >) #Push zero
} #End if
{} #Pop the zero
<> #Switch back
} #End While
<> #Switch to the other stack
({}<{}>) #Remove the second value on the stack #End Mod
( ) #Duplicate the result of modulation
{ #If the top is not zero
{}{} #Pop the top two elements
(<(())>) #Push a one and a zero
} #End if
{} #Pop the zero
ASMD, 3 bytes (non-competing)
%0=
Groovy, 12 chars/bytes
Adding a Groovy version just for the sake of completeness, and for a comparison with the Java 8 snippet above.
Groovy is a Java-based language compiled to JVM bytecode, and was designed with a very concise syntax in mind, allowing less boilerplate code than pure Java. But if failed this time! The actual code is one byte shorter than Java, but needs the curly braces in order to compile as an anonymous closure, making it 1 byte longer at 12 bytes:
{n,d->n%d<1}
To run with n=9, d=3, just do this:
println ({n,d->n%d<1}(9,3))
You can try it online on http://groovyconsole.appspot.com
Python 2, 24 bytes
print input()%input()==0
Brain-Flak, 72 70 64 62 58 46 bytes
{({}[()]{(<()>)}{}<({}[()]<({}())>)>)}{}{{}}{}
Takes dividend and divisor (in that order) as input and prints the divisor (truthy) or nothing. Since each stack has an implicit, infinite amount of zeroes, empty output should be considered falsy.
While not stack-clean, this solution uses only a single stack.
Thanks to @WheatWizard for golfing off 2 bytes!
How it works
INPUT: a (dividend), b (divisor)
INITIAL STACK: n = a, d = b, r = 0
An infinite amount of zeroes follows.
{ While n is non-zero:
(
{} Pop n from the stack.
[()] Yield -1.
{ While the top of the stack (initially, d) is non-zero:
(<()>) Push 0.
}
{} Pop 0. This will remove d from the stack if d = 0, leaving r
on top. We can think of this as performing the assignment
(d, r) = (r, d) if d = 0.
<
(
{} Pop d.
[()] Yield -1.
<
(
{} Pop r.
() Yield 1.
) Push r + 1.
> Yield 0.
) Push d + (-1) + 0 = d - 1.
> Yield 0.
) Push n + (-1) + 0 + 0 + 0 = n - 1.
} Each iteration decrements n, swaps d and r if d = 0, decrements d,
and increments r.
FINAL VALUES: n = 0
d = b - r
r = a % b if a % b > 0 else b
{} Pop n.
{ While the top of the stack is non-zero:
{} Pop it.
} This pops d and r if d > 0 (and, thus, a % b > 0) or noting at all.
{} Pop d or a 0, leaving r if r = b and, thus, a % b = 0.
Modulus calculation, 42 bytes
The above full program can be modified in a trivial manner to calculate the modulus instead.
{({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{}
As before, this method is not stack-clean, but it uses only a single stack. A modulus of 0 will leave the stack empty, which is roughly equivalent to leaving 0; each stack contains infinite zeroes.
How it works
Compare the two loops of the divisibility tester and the modulus calculator.
{({}[()]{(<()>)}{}<({}[()]<({}())>)>)}
{({}[()]<({}[()]<({}())>)>{(<()>)}{})}
The only difference is the location of {(<()>)}{}, which swaps d and r if d = 0. To calculate the modulus, we perform this swap after decrementing d and incrementing r.
This change does not affect the outcome if a %b > 0, but if a % b = 0, it leaves (n, d, r) = (0, b, 0) – rather than (n, d, r) = (0, 0, b) – on the stack.
Thus, to obtain the modulus, we only have to pop n and d with {}{}.
Stack-clean modulus calculation, 64 bytes
The 42-byte modulus algorithm is not stack-clean, so it cannot be used as is in all programs. The following version pops dividend and divisor (in that order) from the active stack and pushes the modulus in return. It has no other side effects.
({}(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}>)
This solution is largely based on @WheatWizard's previous 72-byte record, but it saves 6 bytes by never switching stacks.
How it works
INPUT: a (dividend), b (divisor)
INITIAL STACK: n = a, b
(
{} Pop and yield n = a.
(<()>) Push d = 0.
) Push n + 0 = n.
STACK: n, d = 0, b
{( While n in non-zero:
{} Pop and yield n.
[()] Yield -1.
<
((
{} Pop and yield d.
() Yield 1.
[({})] Pop b, push it back on the stack, and yield -b.
)) Push d + 1 + -b = d + 1 - b twice.
{ While/if d + 1 - b is non-zero, i.e., if d < b - 1
{} Pop d + 1 - b (second copy).
(<(
{} Pop d + 1 - b (first copy).
({}) Pop b and push it back on the stack.
)>) Push d + 1 - b + b = d + 1, then 0.
} If the loop wasn't skipped entirely, pushing 0 breaks out.
If d < b - 1, it essentially performs the assignment d = d + 1.
However, if d = b - 1, we get d = d + 1 - b = b - 1 + 1 - b = 0.
In all cases, we wind up with d = (d + 1) % b.
{} Pop 0.
> Yield 0.
)} Push n + -1 + 0 = n - 1. Break if n - 1 = 0.
STACK: n = 0, d = a % b, b
(
{} Pop and yield n = 0.
{} Pop and d = a % b.
<{}> Pop b, but yield 0.
) Push 0 + a % b + 0 = a % b.
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)
Elixir, 14 bytes
&rem(&1,&2)==0
Anonymous function defined using the capture operator.
Full program with test cases (yes, the . in the function call is mandatory!):
s=&rem(&1,&2)==0
# test cases
IO.puts s.(1,1) # true
IO.puts s.(2,1) # true
IO.puts s.(6,3) # true
IO.puts s.(17,17) # true
IO.puts s.(22,2) # true
IO.puts s.(1,2) # false
IO.puts s.(2,3) # false
IO.puts s.(2,4) # false
IO.puts s.(3,9) # false
IO.puts s.(15,16) # false
Try it online on ElixirPlayground !
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();
}
}
}
Bash, 13 bytes
echo $[$1%$2]
The positive integers n and d are given as command line arguments in that order. The script outputs 0 (success) if n is evenly divisible by d, or a positive integer otherwise (failure).
05AB1E, 2 1 byte
Ö
Was sÖ (Test here) but arguments switched (suggested by @Mego). This allowed me to golf down to 1 byte.
Explanation (old):
s Reverses input e.g. 6, 3 -> 3,6 so that input is in correct order
Ö Checks if (top of stack % second top of stack) == 0 e.g. 6 % 3 == 0
Implicitly prints (1 because 6 % 3 = 0)
Emotinomicon, 16
😼😼😌😨
Explanation:
😼😼😌😨
😼 pushes integer input
😼 pushes integer input
😌 pops n,m; pushes n mod m
😨 pops n; outputs as number
Returns zero for truthy if first integer is divisible by second, returns non-zero for falsy.
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.
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
R, 22 20 bytes
a=scan();!a[1]%%a[2]
As usually, reads two numbers from the input that is terminated by an empty line.
Update: thanks to Jarko Dubbeldam for shaving off 2 bytes (despite the fact that his edit was rejected, it was very helpful!).
GameMaker Language, 32 bytes
return 1>argument0 mod argument1
TI-Basic, 10 bytes
Prompt N,D:not(fPart(N,D
Returns 1 for true or 0 for false
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.
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.
Vitsy, 1 Byte
This is a function that leaves 0 on the stack if true and a non-zero integer on the stack if false.
M
(This is the modulo function.)
(N has been added for output).
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
Logicode, 289 262 bytes
Presenting the language that's more verbose than Java!
circ d(n)->cond n<->0+n/d(n>)
circ e(n)->[
cond n->var a=~((~(d(n)))>)/var a=0
cond (~n)<->var b=a+0/var b=e(a)+1
b
]
circ f(a,b)->cond *a&*b->f(e(a),e(b))/a
circ g(a,b)->!(*(f(b,a)))
circ h(a,b)->cond b->h(e(a),e(b))/a
circ i(a,b)->cond g(a,b)->i(h(a,b),b)/c(a)
I'll post an explanation later, but it's basically a shortened version of my prime checker.
Added a new feature: * (boolean)!
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;
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!
Javascript (ES6) 17 12 11 bytes
a=>b=>a%b<1
- EDIT: Removed 5 bytes because 'a>0' is expected.
- EDIT2: Removed 1 byte thanks to Downgoat.
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
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
Brain-flak 102, 98, 96 bytes
(({}<>))<>{({}[()])<>(({}[()])){{}(<({}[({})])>)}{}({}({}))<>}{}<>([{}]{}){<>(([()])())}({}{}())
Eww. Gross. I might post an explanation, but I barely understand it myself. This language hurts my brain.
Thanks to github user @Wheatwizard for coming up with a modulus example. I probably could not have figured that out myself!
Also, the shorter answer is here.
Possibly incorrect explanation:
(({}<>)) #Push this element onto the other stack
<> #Move back to stack one.
{ #While the top element is non-zero:
({}[()]) # Decrement the number on top
<> # Move to the other stack
(({}[()])) # Push the top element minus one twice
{ # While the top element is non-zero:
{} # Pop the top element
(< >) # Push a zero
({}) # Push the second from top element
[ ] # Evalue this second from top element as negative
({} ) # And push that negative plus the top element
}
{} # Pop the top element
({}({})) # Push the top element plus the second from the top, AND push the second from top
<> # Switch stacks
}
{} #Pop the stack
<> #Switch to the other stack
([{}]{}) #And push the top element minus the second element.
The rest is pretty straightforward.
{ } #While the top element is non-zero:
<> #Move to the other stack
(([()]) ) #Push a negative one
() #AND push the previously pushed value + 1 (e.g. 0)
( ) #Push:
{}{} #The top two elements added together
() #Plus one
Jellyfish, 5 bytes
pN/|i
Input is a list containing [d n].
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.
Haskell, 13 11 bytes
((1>).).mod
This defines a new function (!) :: Integral n => n -> n -> Bool. Since mod n m returns only positive numbers if n and m are positive, we can save a byte by using 1> instead of 0==.
Usage:
ghci> let n!d=1>mod n d
ghci> 100 ! 2
True
ghci> 100 ! 3
False
PowerShell v2+, 20 bytes
!($args-join'%'|iex)
Takes input as two command-line arguments $args, -joins them together into a string with % as the separator, pipes that to iex (short for Invoke-Expression and similar to eval). The result is either 0 or non-zero, so we take the Boolean not ! of that result, which means either $TRUE or $FALSE (non-zero integers in PowerShell are truthy). That Boolean is left on the pipeline and output is implicit.
Alternative versions, also 20 bytes each
param($a,$b)!($a%$b)
!($args[0]%$args[1])
Same concept, just slightly different ways of structuring the input. Thanks to @DarthTwon for providing these.
Examples
PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 24 12
True
PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 24 13
False
PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 12 24
False
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
x86_32 machine code, 8 bytes
08048550 <div7>:
8048550: 99 cdq
8048551: f7 f9 idiv %ecx
8048553: 85 d2 test %edx,%edx
8048555: 0f 94 c0 sete %al
This is my first code golf answer, so hopefully I'm following all the rules.
This first calls cdq to clear out the edx register, then performs signed division on the ecx register, which stores the remainder in edx. The test edx, edx line will set the zero flag if edx is zero, and sete puts a 0 for false if edx was not zero, and puts a 1 for true if edx was 0.
This is just the code snippet that contributes to the byte count, but for testing, here is the C code I wrote with the inline assembly because it's easier this way to handle I/O.
><>, 3 bytes
%n;
Input numbers are assumed to be on the stack. ><> does not have any default truthy or falsy values, so I use 0 as truthy and everything else as falsy. That seems to be allowed. (If not, 1-truthy, 0-falsy, can be done like this in 5 bytes: %0=n;).
3d, 15 bytes
>::%v
;!T'_'F!;
Takes 2 numbers a and b as input, proceed a mod b, prints T if result is 0, F else. Simple and efficient.
Can be golfable, but since I'm still working on the aforelinked interpreter, I might not come back on it for improvement.
I'm just making a little advertising for my esolang ;)
Java, 13 bytes
(a,b)->a%b<1;
This is a java.util.function.BiPredicate<Integer, Integer>.
As something that makes more sense to those who are new to Java, it takes up 37 bytes:
boolean A(int b,int B){return b%B<1;}
As something that compiles, it takes up 46 bytes:
class a{boolean A(int b,int B){return b%B<1;}}
As something that runs, it takes up 104 bytes:
interface a{static void main(String[]A){System.out.print(Integer.decode(A[0])%Integer.decode(A[1])<1);}}
For the sake of completeness, here's a 50-byte lambda that checks if an arbitrarily large integer a is divisible by another arbitrarily large integer b. It's a BiPredicate<BigInteger, BigInteger>.
(a,b)->a.mod(b).equals(java.math.BigInteger.ZERO);
Hexagony, 15, 13, 12 10 bytes
Everybody's favorite hexagon-based language! :D
TL;DR works using magic, unformatted solutions in decreasing byte count:
?{?..>1'%<.@!'/
?{?!1\.'%<@.>
?{?\!1@'%\!(
?{?!1\@'%<
Saved 2 bytes thanks to @MartinEnder's layout wizardry.
@FryAmTheEggman saved 1 byte by using the corners more creatively
Both @MartinEnder and @FryAmTheEggman came up with a 10 byte solution that doesn't print anything for falsely values.
My solution (15):
Unformatted:
?{?..>1'%<.@!'/
Formatted:
? { ?
. . > 1
' % < . @
! ' / .
. . .
@Martin Ender's Solution (13):
Unformatted:
?{?!1\.'%<@.>
Formatted:
? { ?
! 1 \ .
' % < @ .
> . . .
. . .
Explanation:
First, we get the input and take the modulus.
? { ?
. . . .
' % . . .
. . . .
. . .
Then, it checks if the modulus is 0 or not. If it is, the IP turns 60 degrees left, bounces off the mirror, sets the cell to 1 and prints.
Then, the IP continues onto the fourth row. When it reaches the >, it turns to the right instead (because the value of the cell is now 1). It goes oob, and comes back in the bottom right corner heading NW. The IP hits the <, goes along the top row, and comes back in the right corner to hit the @, stopping the program.
. . .
! 1 \ .
. . < @ .
> . . .
. . .
If the modulus turns out to be positive, the IP turns 60 degrees to the right. Once it goes out the bottom right corner, it continues on the bottom left edge because of Hexagony's wrapping rules. The ' is reused to make the IP go to a cell with 0 in it. The IP then travels along the fourth row, wraps around to the second, hits print, and gets reflected into the <. The rest of the path to the @ is the same.
. . .
! . \ .
' . < @ .
> . . .
. . .
That's some serious wizardry.
@FryAmTheEggman's Solution (12):
Unformatted:
?{?\!1@'%\!(
Formatted:
? { ?
\ ! 1 @
' % \ ! (
. . . .
. . .
Explanation:
Like the other solutions, it gets the input and takes the modulus.
? { ?
. . . .
' % . . .
. . . .
. . .
Then, the IP gets deflected into the bottom corner. If the modulus is positive, it goes on the top left edge. The ? has no more input, so it sets the cell to 0. The ! then prints the 0, and the @ terminates the program.
? . .
\ ! . @
. . \ . .
. . . .
. . .
Things are much trickier for when the modulus is 0. First of all, it gets decremented, then reset to 0, then set to 1, then printed. Then, the 1 gets decremented to 0. After that, the program runs like it does at the beginning until it tries to do 0%0. That makes it throw a silent error and quit.
? { ?
. . 1 .
' % \ ! (
. . . .
. . .
I really like the silent error trick, but a simpler way would be to replace the ( with / so that the IP passes through the first time, but gets reflected into @ the second.
Collaborative solution (10):
Unformatted:
?{?!1\@'%<
Formatted:
? { ?
! 1 \ @
' % < . .
. . . .
. . .
This program starts out the same as all the other programs, getting the input and modding it.
If the input is 0, the IP turns left when it hits <. It gets deflected into 1!@, which prints 1 and quits.
. . .
! 1 \ @
. . < . .
. . . .
. . .
If the input is positive, the IP turns right when it hits <. It exits through the corner, and goes along the top right edge hitting the @ without printing.
. . ?
. . . @
. . < . .
. . . .
. . .
q - 9 bytes
An anonymous lambda, returns boolean true/false
not(mod).
Example
q)not(mod). 18 4
0b
q)not(mod). 18 3
1b
Labyrinth, 8 bytes
??
@%
!1
Input is just the two numbers, using any non-numeric separator of your choice. Output is either 1 for truthy or nothing at all for falsy.
Alternative solution that prints 0 for falsy but terminates with an error (same byte count):
<1%??
!;
Explanation
There's only one branch in the execution and that's after the modulo (%). When the input is a truthy case, the following is executed:
? Read integer and push onto stack.
? Read integer and push onto stack.
% Take the first modulo the second integer. The result is zero, so the
instruction pointer keeps moving south.
1 Turn that zero into a one.
! Print it.
@ Terminate the program.
Otherwise, the following code is executed:
? Read integer and push onto stack.
? Read integer and push onto stack.
% Take the first modulo the second integer. The result is positive, so
the instruction pointer turns west.
@ Terminate the program.
Mathematica - 17 13 3 bytes
∣
Thanks to @MartinEnder for saving a ton of bytes!
Batch, 27 bytes
for /l %a IN (1,1,10)DO @%a
Does
' is not recognized as an internal or external command, operable program or batch file.'
count as a separator?
ROOP, 24 bytes
I
w
w
R #H
#
N
#
W
O#
The I is the input object. When the object is on the operator w wait the entry of a number that puts it under. Then the I moves to the right and falls on the second w waiting for the second number. The operator R removes those two numbers, and make the remainder of divide them below. The N operator removes that number and creates a 1 if the number was 0, and 0 otherwise. Then the W operator puts that number in the O object representing the output. At the same time the I reached the operator H that ends execution.
Sesos, 16 bytes
Hexdump:
0000000: d6659c af71e7 a0fbf8 70cedc ae8de7 1e .e..q....p......
Assembler:
set numin
set numout
get,fwd 1,get,rwd 1
jmp
fwd 1,sub 1,fwd 1,add 1,rwd 1
jmp
fwd 2
jnz
fwd 1
jmp
sub 1,rwd 1,add 1,fwd 1
jnz
rwd 3
jmp
rwd 1
jnz
fwd 1
sub 1
jnz
fwd 4,add 1,rwd 2
jmp
fwd 1
jnz
fwd 2
put
Brainfuck: ,>,<[>->+<[>>]>[-<+>]<<<[<]>-]>>>>+<<[>]>>.
dc, 8 7 bytes
Input is delimited by a space: n d
?~/z1-n
If false, it outputs 0. If true, it outputs 1 and throws an error about division by zero.
Explanation:
? # Take input from stdin.
~ # Pop two values from stack. Push quotient. Push remainder.
/ # Attempt to divide quotient by remainder.
# If input is divisible, then remainder is 0.
# Division fails, throwing an error and leaving both numbers on stack.
# (Stack depth is 2.)
# If input is not divisible, then remainder is not 0.
# Division succeeds, and result is pushed on stack. (Stack depth is 1.)
z # Push stack depth on stack. (If divisible, push 2; if indivisible, push 1.)
1- # Subtract 1 from top of stack. ToS is now 1 or 0.
n # Pop top of stack and print it as a number.
Clojure, 15 bytes
#(=(mod % %2)0)
C#, 27 13 12 Bytes
a=>b=>a%b<1;
Thanks to TuukkaX for pointing out anonymous lambdas are acceptable. Thanks to David Conrad for pointing me on to currying which I wasn't even aware was a thing.
Short and sweet, since we're only dealing with integers we can use <1 rather than ==0 and save a whole byte.
J, 3 bytes
0=|
Usage:
2 (0=|) 10
Will return 1. And is equivalent to pseudocode 10 MOD 2 EQ 0
Note this is very similar to the APL answer, because J is heaviliy inspired by APL
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.
PHP, 23 22 bytes
<?=$argv[1]%$argv[2]<1
prints 1 for true, empty string (=nothing) for false
call from cli with n and d as arguments
10 bytes for ancient PHP: <?=$n%$d<1
C, 60 Bytes
#include <stdio.h>
main(){int a,b;scanf("%d %d",&a,&b);a%b==0;}
Tcl , 34 bytes
ge stdin a
ge stdin b
exp $a%$b<1
My first /*successful*/ attempt in codegolf ! This code must be executed in Tcl shell , otherwise it will not work.
One byte thanks to @Lynn .
Four bytes thanks to @Lynn and @LeakyNun (now I understand what he meant)!
MarioLANG, 121 109 107 bytes
Saved 14 bytes thanks to Martin Ender
;>(-)-)+(([!)
)"=========#[
; +({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
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!
Racket, 26 bytes
(λ(n m)(integer?(/ n m)))
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.
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;
}
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
Befunge, 6 bytes
&&%!.@
Try it here! Input two numbers, separated by a space. Output is 0 or 1 for falsy or truthy.
MATL, 2 bytes
\~
\ % Take two inputs implicitly. Compute their modulo
~ % Logical negate. Implicit display
brainfuck, 53 bytes
Takes input as bytes, output is a byte value of 0x00 or 0x01. It's the DivMod algorithm followed by Boolean negation.
,>,<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>,>[<+>,]+<[>-<-]>.
Try it online - Has a bunch of extra + near the end so you can see the output in ASCII.
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.
Vim, 11 keystrokes
C<C-r>=<C-r>"<C-Left>%<C-Right><1<cr>
Not bad for a language that only handles strings. :D
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
Fortran 95, 78 bytes
function f(i,j)result(k)
integer::i,j,k
k=merge(1,0,MOD(i,j)<1)
end function f
Minkolang 0.15, 6 bytes
nn%,N.
Explanation
nn Take two numbers from input
% Pop b, a and push a%b
, NOT top of stack
N. Output as number and stop.
Batch, 20 bytes
@cmd/cset/a!(%1%%%2)
Outputs 1 on success, 0 on failure.
Retina, 12 bytes
^(1+)\1* \1$
Takes space-separated input in unary, like 111111111111 1111 to check if 12 if divisible by 4. Prints 1 (true) or 0 (false).
FryAmTheEggman saved two bytes. Oops, rewrote my answer to take the arguments in the right order. (Then Fry beat me to it in the comments. I’m slow at regex!)
CJam, 6 4 bytes
Saved 2 bytes thanks to Dennis
q~%!
q e# Take in the input
~ e# Dump the individual values to the stack
% e# Modulus
! e# Boolean NOT
GolfScript, 3 bytes
~%!
Explanation:
~ # Evaluate the input
% # Take the first modulus the second
! # Boolean not
Python, 16 bytes
lambda D,d:D%d<1