51
\$\begingroup\$

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!

\$\endgroup\$
12
  • 20
    \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Commented Nov 26, 2014 at 3:37
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 26, 2014 at 3:41
  • 5
    \$\begingroup\$ All whitespace required for the code to work is functional. \$\endgroup\$ Commented Nov 26, 2014 at 3:42
  • \$\begingroup\$ Okay, thanks for the response! \$\endgroup\$ Commented Nov 26, 2014 at 3:47
  • 1
    \$\begingroup\$ @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). \$\endgroup\$ Commented Nov 26, 2014 at 22:07

71 Answers 71

1
\$\begingroup\$

BASH - 117 characters

f(){ [[ $1 =~ 0 ]]&& return 0 || r=;n=$1;for((i=0;i<${#n};i++));do r=$(($r+${n}%${n:$i:1}));done;return $(($r==0));}

tests

for N in 128 12 120 122 13 32 22 42 212 213 162 204; do
  f $N
  echo "${N} ->  $?"
done

128 ->  1
12 ->  1
120 ->  0
122 ->  1
13 ->  0
32 ->  0
22 ->  1
42 ->  0
212 ->  1
213 ->  0
162 ->  1
204 ->  0
\$\endgroup\$
1
\$\begingroup\$

PHP - 74 71 64 Characters

Golfed:

function t($n){while($n>1){if(!($b=$n%10)||($n%$b)){return 0;}$n/=10;}return 1;}

Less Golfed:

function t($n){
    while($n>1){
        if( !($b=$n%10) || ($n%$b) )
            { return 0; }
        $n/=10;
    }
    return 1;
}

Test Results:

(Code)

$ans = array(128,12,120,122,13,32,22,42,212,213,162,204);
foreach($ans as $a)
{ echo "$a -> ".(t($a)?"True":"False").PHP_EOL; }

(Output)

128 -> True
12 -> True
120 -> False
122 -> True
13 -> False
32 -> True
22 -> True
42 -> True
212 -> True
213 -> True
162 -> False
204 -> False
\$\endgroup\$
0
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ You answer seems to fail for 297 (not divisible by 2). \$\endgroup\$ Commented May 9, 2018 at 13:33
1
\$\begingroup\$

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)
\$\endgroup\$
2
  • \$\begingroup\$ The method signature can be whatever you want. Just count the function body. I think this is 11 bytes. \$\endgroup\$ Commented Nov 17, 2017 at 18:38
  • \$\begingroup\$ @EriktheOutgolfer thanks, what an odd rule \$\endgroup\$ Commented Nov 17, 2017 at 21:34
1
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\begingroup\$ @Optimizer I've updated language name, sorry for dissonance. \$\endgroup\$
    – Qwertiy
    Commented Dec 3, 2014 at 11:30
  • \$\begingroup\$ JavaScript, ES6 would be the best choice :) \$\endgroup\$
    – Optimizer
    Commented Dec 3, 2014 at 11:34
  • \$\begingroup\$ @Optimizer Ok :) \$\endgroup\$
    – Qwertiy
    Commented Dec 3, 2014 at 11:38
  • \$\begingroup\$ The f= does not count towards the bytecount, since it's not a recursive function. This is actually 33 bytes. \$\endgroup\$ Commented Dec 18, 2017 at 9:30
  • \$\begingroup\$ @PatrickRoberts, thanks, updated. \$\endgroup\$
    – Qwertiy
    Commented Dec 18, 2017 at 9:54
1
\$\begingroup\$

J, 14 bytes

0=1#."."0@":|]

Try it online!

Small improvement on existing J answer.

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

Vyxal, 3 bytes

fḊg

Try it Online!

Explained

fḊg
f   # flatten input to get list of digits
 Ḋ  # divisible by
  g # minimum value of the individual lists whether the digit is divisible or not. 
    #   If it is, `1`, if not `0`. So if 1 digit is not divisible, it returns `0` in the list, and the program takes it as the minimum.
\$\endgroup\$
1
\$\begingroup\$

Japt, 7 bytes

Handling 0s cost a couple of bytes (x/0 = Infinity).

ìeÈ©UvX

Try it

ìeÈ©UvX     :Implicit input of integer U
ì           :Convert to digit array
 e          :Does each return true
  È         :When passed through the following function as X
   ©        :  Logical AND with
    UvX     :  Is U divisible by X
\$\endgroup\$
1
\$\begingroup\$

Ruby, 32 bytes

->n{n.digits.all?{_1>0&&n%_1<1}}

Attempt This Online!

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

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes

a%f

Try it online!

I really gotta fix a.

a%f # Returns 0 for truthy, "true" for falsey
 %  # Modulo the number
  f # By each of its digits
a   # Any != 0?
\$\endgroup\$
1
\$\begingroup\$

Thunno 2, 3 bytes

dḊp

Attempt This Online!

Explanation

dḊp  # Implicit input   ->  128
d    # Cast to digits   ->  [1,2,8]
 Ḋ   # Divisible?       ->  [1,1,1]
  p  # Product          ->  1
     # Implicit output
\$\endgroup\$
0
\$\begingroup\$

J (16)

+/@:|~_1&(10&#.)

Returns 0 when true, another number otherwise

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

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.

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

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);
}
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 26, 2014 at 22:16
  • \$\begingroup\$ You could golf it to $x=1;foreach(str_split($n)as$i)$x&=$i&&$n%$i==0;return(bool)$x; \$\endgroup\$
    – abc667
    Commented Jan 1, 2015 at 11:50
0
\$\begingroup\$

Mathematica, 53 bytes (46 byte body)

f[x_]:=AllTrue[IntegerDigits@x,#!=0&&Divisible[x,#]&]
\$\endgroup\$
1
  • 1
    \$\begingroup\$ f@x_ := Tr[x~Mod~IntegerDigits[x]] == 0 \$\endgroup\$ Commented Nov 27, 2014 at 17:39
0
\$\begingroup\$

PHP, 59 Characters

Where $n is the number you're checking

foreach(str_split($n)as$v)if($n%$v!=0){echo 0;exit;}echo 1;
\$\endgroup\$
2
  • \$\begingroup\$ You can reduce this code further echo 0;exit; can simply be die('0'); \$\endgroup\$ Commented Nov 27, 2014 at 9:27
  • \$\begingroup\$ One of the requirements is to return the boolean value if supported by the language and PHP certainly has true and false. \$\endgroup\$ Commented Nov 27, 2014 at 17:35
0
\$\begingroup\$

Haskell, 55

let f x =(\s->all(>'0')s||all((<1).(x`mod`).read.(:[]))s)$show x

Counting characters after the = sign as per the rules.

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

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);  
}
\$\endgroup\$
2
0
\$\begingroup\$

Java 7, Score = 96 76

Since I can't compete with your number based method, I used a character based method instead. a has the input integer in it.

int c=0;for(char e:(""+a).toCharArray())c+=(e-=-48)<1||a%e>0?1:0;return c<1;

Here it is golfed indented with structure code:

public class T{

    public static void main(String[] args){
        System.out.println(new T().test(Integer.parseInt(args[0])));
    }

    boolean test(int a){
        int c=0;
        for(char e:(""+a).toCharArray())
            c+=(e-=-48)<1||a%e>0?1:0;
        return c<1;
    }

}

Here it is completely expanded:

public class Test{

    public static void main(String[] args){
        System.out.println(new Test().test(Integer.parseInt(args[0])));
    }

    boolean test(int number){
        String numberString = "" + number;
        int failed = 0;
        for (int a = 0; a < numberString.length(); a++){
            int charAt = numberString.charAt(a) - '0';
            if (charAt == 0 || number % charAt != 0){
                failed++;
            }
        }
        return failed < 1;
    }

}

Edit: Used Mathew Kirschbaum's suggestions to shorten code size.

\$\endgroup\$
2
  • \$\begingroup\$ On first glance, I see a few places where you can shorten this by relatively large amounts. First, you can change for(;d<b.length();d++) to for(char d:b). That form of for is essentially a foreach loop. That will also shorten b.charAt(d) to just d, as well as remove the declaration of d in your second statement. Since b isn't used anywhere in the code other than the for condition anymore, you can get rid of it entirely and just replace the previously changed for(char d:b) to for(char d:a+""). That brings you to 62 or so. \$\endgroup\$ Commented Nov 27, 2014 at 2:56
  • 1
    \$\begingroup\$ According to docs.oracle.com/javase/specs/jls/se7/html/…, you cannot use a for each loop to iterate over a string. You can only iterate over collections and arrays. I'll try to find something that is similar, though. \$\endgroup\$ Commented Nov 27, 2014 at 22:19
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

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

Scala, 38 characters

def isDivisibleByAllDigits(n: Int) = n.toString.forall(d=>d>48&&n%(d-48)<1)
\$\endgroup\$
0
\$\begingroup\$

Python 2, 41 bytes

Size not including f=lambda j:.

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

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ i>"0" Lexicographical comparisons are your friend :) \$\endgroup\$ Commented Nov 27, 2014 at 20:19
  • \$\begingroup\$ @FryAmTheEggman Great, thanks! \$\endgroup\$
    – Beta Decay
    Commented Nov 27, 2014 at 20:21
  • \$\begingroup\$ 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 ... :/ \$\endgroup\$ Commented Nov 27, 2014 at 20:27
  • \$\begingroup\$ I mean j%int(i)<1 >_< \$\endgroup\$ Commented Nov 27, 2014 at 20:35
0
\$\begingroup\$

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)

The fact I beat about half of the answers is surprising.

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

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

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

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 ]; }
\$\endgroup\$
0
\$\begingroup\$

Clojure, 71 bytes

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

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
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 89 81 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}
\$\endgroup\$
2
  • \$\begingroup\$ 1. Sorry for that. 2. I don't see the problem here. Can you please explain? 3. Ok, I'll recalculate. \$\endgroup\$
    – Jamie
    Commented Jul 9, 2015 at 1:21
  • \$\begingroup\$ Why dud you roll back your edit? \$\endgroup\$
    – Dennis
    Commented Jul 9, 2015 at 4:06
0
\$\begingroup\$

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)
Read 3 items
[1] FALSE
> f(128)
Read 3 items
[1] TRUE
> f(12)
Read 2 items
[1] TRUE
> f(213)
Read 3 items
[1] FALSE
> f(212)
Read 3 items
[1] TRUE
> f(42)
Read 2 items
[1] FALSE
\$\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.