# Is a number divisible by each of its digits?

My friend and I were working on a lab in our AP Computer Science class and decided to code golf one one the problems since we still had half the class free after we finished. Here is the question:

Given a number n, is n divisible by each of its digits?

For example, 128 will pass this test- it is divisible by 1,2, and 8. Any numbers with a zero automatically disqualify the number. While you may use other languages and post solutions with them if you like, we are most interested in seeing how compact people can make the program in Java, as that is the language we use in the class. So far, we both have 51. Here is my current code:

public boolean dividesSelf(int n){for(int p=n;n%10>0;)n/=p%(n%10)>0?.1:10;return n<1;}
// 51 characters

// Breakdown:
// for(int p=n;         Saves one semicolon to put declaration into for loop
// n%10>0;)             Basic check-for-zero
// n/=                  Pretty simple, discarding one number off of n at a time
// p%(n%10)>0?          If p (the given value) is not divisible by n%10 (the current digit)...
// .1:10;               Divide by .1 (multiply by 10) so it fails the check next iteration. If it is divisible, divide by 10 to truncate the last digit
// return n<1           If the number was fully divisible, every digit would be truncated, and n would be 0. Else, there would still be non-zero digits.


## Requirements

The method signature can be whatever you want. Just count the function body. Make sure, though, that the method returns a boolean value and only passes in one numeric parameter (not a string).

The code must be able to pass all of these cases (in order to stay true to the directions of the original question, only boolean true and false values count if the language supports booleans. If and only if your language does not have boolean variables you may represent false with 0 and true with any nonzero integer (preferably 1 or -1):

128 -> true
12 -> true
120 -> false
122 -> true
13 -> false
32 -> false
22 -> true
42 -> false
212 -> true
213 -> false
162 -> true
204 -> false


Also, we didn't count whitespace, so feel free to do the same, unless the whitespace is essential to the working of the program (so newlines in Java don't count, but a single space between int and x=1 does count.) Good luck!

• Welcome to PPCG! A few suggestions: 1. Not counting functional whitespace is a bad idea. Any answer written in Whitespace will automatically win. 2. Should our submission print/return true and false or are truthy/falsy values OK as well? 3. The java tag doesn't really apply here, as the challenge itself is unrelated to Java. – Dennis Nov 26 '14 at 3:37
• Okay. sorry for the issues. Just to clear it up, would you consider the space in 'int p=n' to be functional, because I did not previously. I will fix the other issues you pointed out. – Mathew Kirschbaum Nov 26 '14 at 3:41
• All whitespace required for the code to work is functional. – FryAmTheEggman Nov 26 '14 at 3:42
• Okay, thanks for the response! – Mathew Kirschbaum Nov 26 '14 at 3:47
• @RickyDemer: since 0 would be an exceptional input in that case (it's the only number with 0 digits that is a multiple of each of them), I imagine most answers would just get longer in an uninteresting way to include a check for it. So I like the problem as posed by the title better (divisible by its digits, rather than being a multiple of its digits, which excludes 0). – Jeroen Mostert Nov 26 '14 at 22:07

# PHP: 45 Characters

The character count is for the body of the function.

It is necessary to only pass the first parameter.

function t($n,$k=true, $s='str_split'){foreach($s($n)as$b)$k=$k&&$n%$b===0;return$k;}  • "and only passes in one numeric parameter" – abc667 Jan 1 '15 at 11:36 # 05AB1E, 6 5 bytes Ñ¨K0‹  Try it online! # Explanation Ñ¨K0‹ full program with implicit input [213] Ñ push divisors [1, 3, 71, 213] ¨ remove the last element [1, 3, 71] K push a without b [2] 0 push 0 [2] [0] ‹ push a < b [0] output implicitly  K uses the implicit input [213] as a and the current stack [1, 3, 71] as b. • You answer seems to fail for 297 (not divisible by 2). – Kevin Cruijssen May 9 '18 at 13:33 # Stacked, 11 bytes in the function body [:10 tb\|all]  Try it online! Takes a number from the stack and returns 1 if they are all divisible or 0 otherwise. ## Explanation [:10 tb\|all] [ ] anonymous function (the function body) :10 tb push digits of the number (*t*o *b*ase 10) \| vectorized "divides" test all ensure all are truthy (i.e. not 0)  • The method signature can be whatever you want. Just count the function body. I think this is 11 bytes. – Erik the Outgolfer Nov 17 '17 at 18:38 • @EriktheOutgolfer thanks, what an odd rule – Conor O'Brien Nov 17 '17 at 21:34 ## Javascript ES6, 33 n=>(""+n).replace(/./g,x=>n%x)==0  Test: f=n=>(""+n).replace(/./g,x=>n%x)==0 console.log( [128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204] .map(f) == "true,true,false,true,false,false,true,false,true,false,true,false" ) • @Optimizer I've updated language name, sorry for dissonance. – Qwertiy Dec 3 '14 at 11:30 • JavaScript, ES6 would be the best choice :) – Optimizer Dec 3 '14 at 11:34 • @Optimizer Ok :) – Qwertiy Dec 3 '14 at 11:38 • The f= does not count towards the bytecount, since it's not a recursive function. This is actually 33 bytes. – Patrick Roberts Dec 18 '17 at 9:30 • @PatrickRoberts, thanks, updated. – Qwertiy Dec 18 '17 at 9:54 # J (16) +/@:|~_1&(10&#.)  Returns 0 when true, another number otherwise ## Python 2, ~85 ~83 characters (~75 ~73 just the function body) Staying all numeric; count includes newlines and spacing. def t(n): r=n while r: r,i=divmod(r,10) if not i or n%i:return 0>1 return 1>0 assert(t(128)==True) assert(t(12)==True) assert(t(120)==False) assert(t(122)==True) assert(t(13)==False) assert(t(32)==False) assert(t(22)==True) assert(t(42)==False) assert(t(212)==True) assert(t(213)==False) assert(t(162)==True) assert(t(204)==False)  Alternative, 88 characters in the function body: def t(n):return '0' not in n and not reduce(lambda a,b:a or b,[divmod(n,int(x))[1] for x in n])  The approach feels shorter with map/reduce but with Python code it isn't. # PHP - 91 characters function divides($n) {
foreach(array_map('intval', str_split($n))as$i)if($i==0||$n%$i!=0)return false;return true; } foreach ([128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204] as$n) {
echo "\n" . $n . ' -> ' . divides($n);
}

• This is code golf, so please shorten your code as much as you can (e.g. by removing unnecessary whitespace) and include byte count in your answer. – Martin Ender Nov 26 '14 at 22:16
• You could golf it to $x=1;foreach(str_split($n)as$i)$x&=$i&&$n%$i==0;return(bool)$x; – abc667 Jan 1 '15 at 11:50

# Mathematica, 53 bytes (46 byte body)

f[x_]:=AllTrue[IntegerDigits@x,#!=0&&Divisible[x,#]&]

• f@x_ := Tr[x~Mod~IntegerDigits[x]] == 0 – Dr. belisarius Nov 27 '14 at 17:39

Where $n is the number you're checking foreach(str_split($n)as$v)if($n%$v!=0){echo 0;exit;}echo 1;  • You can reduce this code further echo 0;exit; can simply be die('0'); – Hanky Panky Nov 27 '14 at 9:27 • One of the requirements is to return the boolean value if supported by the language and PHP certainly has true and false. – rink.attendant.6 Nov 27 '14 at 17:35 # Haskell, 55 let f x =(\s->all(>'0')s||all((<1).(xmod).read.(:[]))s)$show x


Counting characters after the = sign as per the rules.

## Java 104

Uses recursion. This test (i==0) is required to stop divide by zero error.

public boolean d(int n,int k)
{
int i=k%10;return (k<10)?(k>0)&&(n%k==0):(i==0)?false:(n%i==0)&d(n,k/10);
}

• All ==0 can be shortened to <1. (i==0)?false: can be replaced by (i>0)&&. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Nov 28 '14 at 12:03
• (k<10)?(k>0)&&(n%k==0): can be replaced by (n>0)&(k<1)||. We will let the function recurse once more and check the base case there. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Nov 28 '14 at 12:26

## Batch - 202 Bytes

Takes input from stdin - C:\div.bat 128.

@echo off&setLocal EnableDelayedExpansion&set s=%1&set c=%1&set l=0
:c
if defined s set/Al+=1&set "s=%s:~1%"&goto c
for /l %%a in (1,1,!l!)do set/aa=%c%%%%%a&if !a!==1 echo false&goto :EOF
echo true


# Java - (64)

This is the shortest I can come up with:

boolean t(int a) {
int x=a,t=0;do t+=x%10>0?a%(x%10):0;while((x/=10)>0);return t<1;
}


If you don't count the method overhead, just the body, it scores 64.

# Scala, 38 characters

def isDivisibleByAllDigits(n: Int) = n.toString.forall(d=>d>48&&n%(d-48)<1)


# Python 2, 41 bytes

Size not including f=lambda j:.

f=lambda j:all(j%int(i)==0if i>"0"else 0for i inj)


Argument supplied must be an integer.

Basically what this does is iterates through the integer (after converting it to a string) and checks the divisibility.

• i>"0" Lexicographical comparisons are your friend :) – FryAmTheEggman Nov 27 '14 at 20:19
• @FryAmTheEggman Great, thanks! – Beta Decay Nov 27 '14 at 20:21
• You know.. sometimes I think I must be crazy. This is twice that I've seen the lexical golf, but not the numeric one... j%int(i)>0 ... :/ – FryAmTheEggman Nov 27 '14 at 20:27
• I mean j%int(i)<1 >_< – FryAmTheEggman Nov 27 '14 at 20:35

# ES6, not exactly a golf, just screwing around with the Y-combinator

let dividesSelf = v =>
!(l =>
(f => f(f))
(f => l(n => f(f)(n))))
(f => n => n + v % n)
(v >> 1);


A little minified, 52 characters long

let dividesSelf = v =>
!(l=>(f=>f(f))(f=>l(n=>f(f)(n))))(f=>n=>n+v%n)(v>>1)


# Go - 47 chars

func dividesSelf(i int) bool {
for n:=i;i%10>0&&n%(i%10)<1;i/=10{};return i==0
}


Runnable on Go Playground: http://play.golang.org/p/67DQXWnwOT

## Bash, 49

Exits with 0 if the number is divisible, other exit code (and a warning) if not.

f () { [ <<<$1 sed "s/./+$1%\0/g"|cut -c2-|bc -eq 0 ]; }


# Clojure, 71 bytes

(fn[n](every? integer?(map #(if(=\0 %1)1.1(/ n(- 48(int %1))))(str n))))


# JAGL Alpha 1.2 - 24 bytes

Obviously this wouldn't count in a real contest, because the language came out after the question, but I'm still gonna answer just for fun. Assumes that the number is the only value on the stack, and sets the top value of the stack to 1 or 0, depending on whether the number is divisible by its digits or not.

dg{i}/d0en{{SdcS%n}/A}Sf


Explanation:

dg                         Duplicate number and convert to string
{i}/                     Convert that to an array of digits
0en                  If 0 is in the array, push 0, else push 1
{                 Block to be run if 0 not in array
{SdcS            Swap, duplicate, cycle, swap
%n}         Push 1 if divisible by digit, 0 otherwise
/A       Map over list and push 1 if all values are 1, otherwise 0
}Sf    Run block if 0 not in array


# JavaScript, 8981 70 bytes

function d(n){a=(n+"").split("");for(i in a)if(n%a[i]||1/0==n/a[i])return!1;return!0}

• 1. Sorry for that. 2. I don't see the problem here. Can you please explain? 3. Ok, I'll recalculate. – Jamie Jul 9 '15 at 1:21
• Why dud you roll back your edit? – Dennis Jul 9 '15 at 4:06

# R, 40 chars

f=function(n)all(n%%scan(t=gsub("(.)","\\1 ",n))%in%0)


%% is vectorized. scan(t=gsub("(.)","\\1 ",n) is a trick that I stole from an old answer by flodel, to split a number into its digits. %in%0 instead of simply negating the results allows for detection of NA (resulting from mod 0; NA==0 gives NA, !NA gives NA but NA%in%0 gives FALSE).

> f(120)
[1] FALSE
> f(128)
[1] TRUE
> f(12)
[1] TRUE
> f(213)
[1] FALSE
> f(212)
[1] TRUE
> f(42)
[1] FALSE


# Javascript, 8281 80 bytes

a=prompt(q=1);b=a.split('');while(d=b.pop())q=q&!(a%d);alert(a.indexOf(0)+1?0:q)


# TI-BASIC, 29

Input X
int(10fPart(X10^(-randIntNoRep(1,1+int(log(X
not(max(remainder(X,Ans+2Xnot(Ans


To disqualify numbers that contain zeroes, I replace all zeroes with 2X, which will not divide X.

I don't count the Input X in the code size, because it is analogous to a method signature.

# Hassium, 130 Bytes

func i(n){m=n.toString();if(m.contains("0"))return false;foreach(d in m)if(n%d.toString().toDouble()!=0)return false;return true;}


Run and see expanded version here

# K (oK), 13 bytes

Solution:

f:{~+/(48!$x)!'x}  13 bytes excludes function definition (+4) per specification. Try it online! Examples: f 1024 0 f 128 1 f 333 1 f 334 0  Explanation: Evaluation is performed right-to-left. Convert (e.g.) 128 => 1 2 8. 128 mod each 1 2 8 => 0 0 0. Sum of this is 0. Not of this is 1: f:{~+/(48!$x)!'x} / the solution including function definition
f:{             } / assign lambda function to f
x  / implicit single parameter
!'   / mod (!) each-left with each-right
(     )     / do this together
$x / string x, 128 => "128" 48! / mod ascii values with 48, "128" => 1 2 8 +/ / sum over results ~ / not, 0 => 1, anything else => 0  # PHP, 44 bytes function f($n,$s=str_split){ foreach($s($n)as$d)$f|=!$d||$n%$d;return!\$f;
}


# Jelly, 3 bytes

ọDẠ


Try it online!

This is a link, i.e. a function in Jelly. Since Jelly doesn't have specific boolean values, this returns 1 for True and 0 for False.

# Python 2: 36 38 Bytes

Excluding f=lambda n:

f=lambda n:all([not n%(int(a)or n-1)for a inn])


Similar to the other python solution. Works because x or 0 returns x if x != 0.

Maybe some edge cases around 0-3 or something.

Edit: Didn't work, fixed it

# J, 18 Bytes (21 with function definition)

d=:0:=+/@:(|~"."0@":)


Explanation:

d=:                     | Define d
":    | Format into string
"."0       | Turn into array of digits
|~           | Starting Number mod each element
+/                | Sum
0:=                  | Test if it’s equal 0. Returns 1 for true, 0 for false


Other characters are for ensuring functions compose properly.