Is a number divisible by each of its digits?

47

7

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!

Mathew Kirschbaum

Posted 2014-11-26T03:25:28.343

Reputation: 571

18

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 – 2014-11-26T03:37:24.680

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 – 2014-11-26T03:41:44.830

5All whitespace required for the code to work is functional. – FryAmTheEggman – 2014-11-26T03:42:15.673

Okay, thanks for the response! – Mathew Kirschbaum – 2014-11-26T03:47:00.307

Just count the calculation inside the brackets - does this apply to all languages that can define functions? – August – 2014-11-26T04:26:34.693

Yes, only count the code that is actually doing work, so ignore anything that defines the function but does not contribute to the actual implementation. Hopefully that clears it up. – Mathew Kirschbaum – 2014-11-26T04:42:03.673

Note that 0 is a multiple of 0, which makes me wonder how the answers would change if you didn't specifically exclude that. – None – 2014-11-26T16:35:42.780

One parameter, ok, but string type or numeric? – edc65 – 2014-11-26T16:37:16.240

Numeric inputs only. – Mathew Kirschbaum – 2014-11-26T17:46:10.670

1@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 – 2014-11-26T22:07:09.320

I'm tempted to suggest the alternate interpretation of the question, in which dividing 123412341234 by 3 yields [12, 412, 412, 4]. – keshlam – 2014-11-28T04:39:11.670

Answers

23

Perl 6, 13

sub golf($_) {
   $_%%.comb.all
}

Uses the implicit variable $_$_ %% .comb.all is equivalent to $_ %% all($_.comb). %% is the "is divisible" operator, and comb with no additional argument returns a list of the characters in a string. As an example, if the argument is 123, then the function evaluates

123 %% all(123.comb)

which is

123 %% all(1, 2, 3)

junction autothreading makes it

all(123 %% 1, 123 %% 2, 123 %% 3)

which is

all(True, False, True)

which is false in boolean context because it's an "all" junction and clearly not all of its elements are true.

It should be possible to coerce the return value to Bool and hide the junction-ness from callers by making the function signature sub golf($_ --> Bool()), but coercions in function signatures don't work yet in Rakudo. The return value is still correctly true or false, it's just not True or False.

hobbs

Posted 2014-11-26T03:25:28.343

Reputation: 2 403

If you want to make it return a Bool just add so to the front of the code so$_%%.comb.all. – Brad Gilbert b2gills – 2014-11-28T13:44:36.687

21

C# and System.Linq - 26 / 40

Per the rules, not counting the method declaration itself.

bool dividesSelf(int i) { 
    return(i+"").All(d=>i%(d-48d)<1);
}

Showing that once again, C# is the superior choice when Java is under consideration... I kid, I kid!

Unfortunately, this function (and many in other answers) will not produce correct results for negative input. We can fix this, but the solution loses a lot of its charm (and grows to 46 characters in length):

return(i+"").All(d=>d>48&&i%(d-48)==0||d==45);

Edit: shaved off one character with Tim's suggestion.

Edit: with the introduction of expression-bodied members in C# 6, we can pare this down further by cutting out the return:

bool dividesSelf(int i) =>
    (i+"").All(d=>i%(d-48d)<1);

for a total of 26 characters (in my opinion, the => should not be included any more than braces would be). The version handling negative numbers can be similarly shortened.

Jeroen Mostert

Posted 2014-11-26T03:25:28.343

Reputation: 311

Are you allowed to use lambda syntax to get rid of the pesky return and trailing semi-colon? i.e. Func<int, bool> dividesSelf = (i) => (i+"").All(d=>i%(d-48d)<1). In the negative case, you perhaps could use the non short circuit version of& vs && :) – StuartLC – 2017-11-17T05:19:47.540

1@StuartLC: lambdas aren't methods; their scope is different, so I think that's bending the rules too far. But since C# 6 (which this answer predates), we have expression-bodied members, which do allow us to shorten the definition. For the negative case, we can't use &, precisely because & doesn't short-circuit -- you'll get a divide by zero exception on the %. We can fix that by making it a double (with d), but then we've lost one character again. – Jeroen Mostert – 2017-11-17T11:25:20.620

Good point :) One day we'll hopefully not need explicit return keyword and possibly also allow for functional return type inference, to bring us inline with other functional languages. – StuartLC – 2017-11-17T11:52:43.340

Why .0? There's no need for anything other than integer modulus. – Peter Taylor – 2014-11-26T09:34:29.887

3@PeterTaylor: There is if you want the shortest program -- i % 0 with i an integer gives a DivideByZeroException. – Jeroen Mostert – 2014-11-26T09:36:52.610

2And with a double it gives NaN! Nice! – Peter Taylor – 2014-11-26T09:39:10.890

248d is the same as 48.0, but one less character (d for double). – Tim S. – 2014-11-26T21:10:14.233

Nice solution... good to see someone finally bring it with C# – Brandon – 2014-11-27T12:56:04.077

@JeroenMostert :) hehe well that'll teach me to blurt out stuff without checking myself. (eh, probably not, seems i've learned that particular lesson about 1,000 times.) tks for the response. i have deleted my comment so that it wouldn't be there to confuse the issue if someone didn't read further. – shelleybutterfly – 2014-12-01T17:41:04.673

18

APL (13 11)

(apparently the brackets don't count)

{0∧.=⍵|⍨⍎¨⍕⍵}

Explanation:

  • ⍎¨⍕⍵: evaluate each character in the string representation of
  • ⍵|⍨: for each of those, find the modulo of it and
  • 0∧.=: see whether all of those are equal to 0

Testcases:

      N,[.5] {0∧.=⍵|⍨⍎¨⍕⍵} ¨ N←128 12 120 122 13 32 22 42 212 213 162 204
128 12 120 122 13 32 22 42 212 213 162 204
  1  1   0   1  0  0  1  0   1   0   1   0

marinus

Posted 2014-11-26T03:25:28.343

Reputation: 30 224

3One character shorter with a train instead of dfn: (0∧.=⍎¨∘⍕|⊢) – ngn – 2014-12-30T01:48:24.247

APL can do X%0 ? without throwing ? – Optimizer – 2014-11-26T11:43:08.907

@Optimizer: yes. 0|X gives X. – marinus – 2014-11-26T11:46:08.523

Sweet. Also your answer is 11 bytes, not 13 – Optimizer – 2014-11-26T11:47:09.660

Also, you are using 4 bytes in the final computation. Do you have a sum of array method ? If yes, do that and Boolean not it. – Optimizer – 2014-11-26T11:48:04.330

@optimizer: That doesn't work in APL. Boolean not (~) expects an actual boolean value (0/1) and will give a DOMAIN ERROR if given something else. You could do ~×+/ (not of sign of sum) but that's also 4 bytes. – marinus – 2014-11-26T11:49:32.153

9Only APL would not give an error on modulo by 0, and crash on evaluating a non-bool as a bool ;) – FryAmTheEggman – 2014-11-26T13:59:17.913

14

Perl - 27 bytes

sub dividesSelf{
    $_=pop;s/./!$&||$_%$&/ger<1
}

Not counting the function signature, as instructed.

Sample Usage:

use Data::Dump qw(dump);
for $i (128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204) {
  printf "%3d -> %s\n", $i, dump(dividesSelf $i);
}

Sample Output:

128 -> 1
 12 -> 1
120 -> ""
122 -> 1
 13 -> ""
 32 -> ""
 22 -> 1
 42 -> ""
212 -> 1
213 -> ""
162 -> 1
204 -> ""

Addressing the problem specification: "Only boolean true and false values count. Truthy/falsey values do not count."

use Data::Dump qw(dump);
dump(1 == 1);
dump(0 == 1);

Outputs:

1
""

'True' and 'False' are defined as 1 and "".

Erratum:
As Brad Gilbert rightly points out, perl defines true as a scalar which is both the integer 1 and the string "1" simultaneously, and false as a scalar which is both the integer 0 and the string "" simultaneously.

primo

Posted 2014-11-26T03:25:28.343

Reputation: 30 891

This can be shortened by not using $_: pop=~s///ger<1. I don't know whether the OP will agree that 1 and "" are valid results. If not, then it can be fixed with two more bytes: just add |0. – hvd – 2014-11-26T14:08:56.123

perl -pe'$_=s/./!$&||$_%$&/ger<1|0' is 26 bytes including the |0 and -p flag. You don't have to use a function. – hmatt1 – 2014-11-26T15:38:48.613

@hvd the inner logic contains $_ as well. Using "@_" in both places is one byte longer. – primo – 2014-11-26T16:36:19.460

@chilemagic this reads from STDIN and writes to STDOUT, rather than being a function as requested. I was tempted to include my($n)=@_; as part of the 'method signature', but it seems a bit of a stretch. – primo – 2014-11-26T16:38:41.973

I can't link to a comment, but op's comment on this answer says it is okay if it isn't a function. I guess it is unclear whether STDIN to STDOUT is allowed.

– hmatt1 – 2014-11-26T16:42:55.020

@primo Oops, you're right. I did test before commenting, but the way I tested was wrong: I was calling the sub in a loop with $_. Sorry about that. Normally I'd delete my earlier comment, but the part about |0 may still make it worth leaving up. – hvd – 2014-11-26T17:04:47.113

1Actually the True and False values are more like dualvar(1,'1') and dualvar(0,''). – Brad Gilbert b2gills – 2014-11-28T13:48:16.940

1@BradGilbert That is interesting. I am reasonably familiar with perlguts, but I wasn't aware that true and false were special cased. They're actually 'triple scalars', marked as SVIV (int), SVNV (double), and SVPV (string). – primo – 2014-11-28T14:59:58.377

1Actually the first time you use a string as a number or a number as a string, the variable gets modified to hold that additional data. That is why you only get a warning the first time you use 'abc' as a number (assuming you have use warnings; enabled. ) – Brad Gilbert b2gills – 2014-11-28T15:43:55.650

@BradGilbert Indeed: http://codepad.org/9VszodfA

– primo – 2014-11-28T15:51:11.473

14

Python 2: 43 chars

f=lambda n:any(n%(int(d)or.3)for d in`n`)<1

Checks whether the number has any nonzero remainders modulo its digits, and outputs the negation of that. Zero digits are handled strangely: since computing %0 causes an error, digits of 0 are replaced with .3, which seems to always give a nonzero result due to floating point inaccuracies.

The function body is 32 chars.

xnor

Posted 2014-11-26T03:25:28.343

Reputation: 115 687

13

CJam, 11 10 bytes

{
    _Ab:df%:+!
}:F;

This defines a function named F and discards the block from the stack.

Try it online.

Test cases

$ cjam <(echo '{_Ab:df%:+!}:F;[128 12 120 122 13 32 22 42 212 213 162 204]{F}%p')
[1 1 0 1 0 0 1 0 1 0 1 0]

How it works

_      " Copy the integer on the stack.                                          ";
Ab     " Push the array of its digits in base 10.                                ";
:d     " Cast each digit to Double.                                              ";
f%     " Take the integer on the stack modulus each of its digits.               ";
:+     " Add the results.                                                        ";
!      " Push the logical NOT of the sum.                                        ";

Dennis

Posted 2014-11-26T03:25:28.343

Reputation: 196 637

Did CJam have the features you used for the 10-byte solution when the question was written? – lirtosiast – 2015-07-08T01:40:02.437

@ThomasKwa: Yes it did. I've tested the code in version 0.6.2, which was released in July 2014. – Dennis – 2015-07-08T02:34:43.830

12

JavaScript ES6, 39 32 28 bytes

v=>[...""+v].every(x=>v%x<1)

Thanks core1024 for the suggestion to replace (""+v).split("") with [...""+v], and openorclose for suggesting the use of every function.

The answer currently doesn't contain one bit of my code :O

Previous solution

v=>[...""+v].filter(x=>v%x|!+x)==""

=="" is not a valid way to check if an array is empty, since [""]=="" returns true, but the array is guarantee to contain non-empty string, so it works here.

The rest are quite standard shorthand type conversion in JavaScript.

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 2014-11-26T03:25:28.343

Reputation: 5 683

v=>![...""+v].some(x=>v%x) – l4m2 – 2017-12-17T21:45:47.560

@l4m2 Since v%0 returns NaN and NaN == false, so in your case numbers that contains 0, such as 10, may return true. – Shieru Asakoto – 2017-12-18T04:26:33.610

Btw shouldn't the answer be 28 bytes long? – Shieru Asakoto – 2017-12-18T04:27:54.567

@user71546: Fixed the character count. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2017-12-18T05:06:57.937

1You can save some characteras by replacing (""+v).split("") with [...""+v]. – core1024 – 2014-11-26T11:53:53.953

1Why not use the every method? v=>[...""+v].every(x=>v%x<1); – openorclose – 2014-11-27T02:24:10.723

@openorclose: Thanks. Never had a chance to use it in JS, so I never thought of searching for such function. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-11-27T02:35:28.917

9

Java 8, 46 Bytes (method body)

Using Jeroen Mostert's converting to double trick.

public static boolean dividesSelf(int n) {
    return(""+n).chars().allMatch(x->n%(x-48d)<1);
}

c.P.u1

Posted 2014-11-26T03:25:28.343

Reputation: 1 049

8

Pyth, 12 bytes

!f|!vT%vzvTz

This filters the characters in the string for being either zero (!vT) or not dividing the input (%vzvT), then takes the logical not of the resulting list.

Try it here.

isaacg

Posted 2014-11-26T03:25:28.343

Reputation: 39 268

No, I'm fine if a function is not used. I just wanted to point out to anybody that was using functions that they do not need to count the declaration, and only the code inside. – Mathew Kirschbaum – 2014-11-26T13:24:34.390

8

Ruby, 44 bytes (function body: 37)

Probably has potential to be golfed further.

f=->n{n.to_s.chars.all?{|x|x>?0&&n%x.hex<1}}

Input taken through function f. Example usage:

f[128] # => true
f[12]  # => true
f[120] # => false
...

August

Posted 2014-11-26T03:25:28.343

Reputation: 706

1You can change .to_i to .hex, since single-digit numbers are the same in base 16, and can change ==0 to <1. – histocrat – 2014-11-26T16:12:25.683

8

Python - 59 50 49 47 bytes

f=lambda n:all(c>'0'and 0==n%int(c)for c in`n`)

I'm sure there's a faster way... oh well.

Edit - Thanks to FryAmTheEggman for the golfing tips.

Edit 2 - FryAmTheEggman may as well have written this at this point, oops

Edit 3 - Hands up if you didn't even know genexps were a thing. ...Just me?

Kasran

Posted 2014-11-26T03:25:28.343

Reputation: 681

Oh, thanks a lot! I keep forgetting about all those things. (I also didn't realize you could less-than chars in that way.) – Kasran – 2014-11-26T05:06:47.460

Oh, flipping the logic also seems to shorten it a bit: f=lambda n:all([c>'0'and 0==n%int(c)for c in\n`])`. And no problem :) – FryAmTheEggman – 2014-11-26T05:11:49.167

Oh, I didn't realize there even was an all method. – Kasran – 2014-11-26T05:12:58.717

Would 1>n%int(c) work? – Sp3000 – 2014-11-26T08:36:27.720

3Why a list-comprehension? Using a genexp: all(c>'0'and 0==n%int(c)for c in`n`) does exactly the same, with 2 char less and even saving the allocation of the list. – Bakuriu – 2014-11-26T10:33:45.033

8

Pyth 11

!f%Q|vT.3`Q

This combines @isaacg's and @xnor's answers. It filters out digits from the input by checking the value of input % (eval(current_digit) or .3). Then it checks if the resulting string is empty or not.

Came across another couple same-length variants:

!f%Q|T.3jQT
!f|!T%QTjQT

Try it online.

FryAmTheEggman

Posted 2014-11-26T03:25:28.343

Reputation: 16 206

5

Bash + coreutils, 44 bytes

The full function definition is:

f()((`tr 0-9 \10<<<$1``sed "s/./||$1%&/g"<<<$1`))

I'm not sure how to score this as normally shell functions use a single set of {} or () to contain the function body. I found here I could also use double (()) to contain the function body which causes an arithmetic expansion which is what I need here. So for now I am counting just one pair of those brackets - further discussion of this is welcome.

Output:

$ for i in 128 12 120 122 13 32 22 42 212 213 162 204; do f $i; printf "%d " $?; done
1 1 0 1 0 0 1 0 1 0 1 0 $
$

Digital Trauma

Posted 2014-11-26T03:25:28.343

Reputation: 64 644

Uh - its not clear to me whether 1s and 0s are acceptable or if I have to print true/false? – Digital Trauma – 2014-11-26T05:21:36.007

4

J - 14 char

The function body is the portion after the =:. If we want to minimize the character count for the whole function, that's the 15 char */@(0=,.&.":|]).

f=:0*/@:=,.&.":|]

,.&.": is the shortest way in J to expand as number into a list of its decimal digits: convert to string, separate the digits, and convert each digit back into a number. ,.&.":|] takes the input number (]) modulo (|) those digits. 0*/@:= returns true if all the results were 0, else gives a false.

   f 162
1
   f every 204 212 213
0 1 0

algorithmshark

Posted 2014-11-26T03:25:28.343

Reputation: 8 144

3

Java - 121 102 97 79 78 bytes

I just know this will get clobbered later. Oh well.

boolean b(int a){int m=10,j,t=1;for(;m<a*10;m*=10){j=10*(a%m)/m;if(j==0||a%j>0)t=0;}return t>0;}

I'll be back.

Stretch Maniac

Posted 2014-11-26T03:25:28.343

Reputation: 3 971

1You can now name your function whatever you want. I changed the rules so you only count the calculations inside the actual function, but the function must return a boolean type. So that is currently at 86 characters. – Mathew Kirschbaum – 2014-11-26T04:00:57.053

3

Haskell - 100 54 38

f x=all(\y->y>'0'&&x`mod`read[y]<1)$show x

Still learning, critiques appreciated

globby

Posted 2014-11-26T03:25:28.343

Reputation: 1 132

I had a comment here, but I accidentally deleted it somehow... Anyway, some suggestions:

  1. Drop the lengths, they are unnecessary.
  2. Replace t by its definition.
  3. elem y s is unnecessary.
  4. /='0' can be moved to the left filter, in place of elem y s.
  5. In this case, /='0' is equivalent to >'0', since every letter is a digit.
  6. Put mod in backticks, so it becomes infix.
  7. Put everything on a single line.
  8. < – Zgarb – 2014-11-26T17:31:14.247

1 and 3 were from when I was trying to do it a different way and salvaged code. Thanks for the tips. – globby – 2014-11-27T05:37:53.130

1my suggestions: instead of using s==filter(...)s you should use all(...)s. now, because s only appears once in the expression, you can replace it with it's definition and drop where. also, instead of ==0 you could use <1. – proud haskeller – 2014-11-28T16:23:56.947

great improvement from the first version! – proud haskeller – 2014-11-28T16:27:32.997

I think you can still lose one byte if you replace all(\y->...)$show x by and[...|y<-show x]. – Zgarb – 2014-12-01T13:02:15.213

You actually gain a byte. and[y|y<-show x,y>'0'&&x\mod`read[y]<1]` – globby – 2014-12-01T17:12:25.080

2

CJam, 15 bytes

{_Abf{_{%}1?}1b!}

{} is the closest thing to a function in CJam. I am just counting the body of the function

Use it like this:

128{_Abf{_{%}1?}1b!}~

To get either 1 (if the number is divisible) or 0 (if the number is not divisible by its digits).

Try it online here

Explanation

_Ab                "Copy the number and split it to its digits";
   f{      }       "For each digit, run this code block on the number";
     _{%}1?        "If the digit is 0, put 1, otherwise perform number modulus digit";
            1b     "We now have an array of modulus corresponding to each digit. Sum it up";
              !    "Negate the sum. If all digits were divisible, sum of modules will be"
                   "0, thus answer should be 1 and vice versa";

Optimizer

Posted 2014-11-26T03:25:28.343

Reputation: 25 836

I might be missing something, but after quickly reading up on CJam, some things seems to not make sense: how does Ab split the digits? It seems to just convert it to base 10. Also, how does % know to mod by the number, and not just the next digit, since it seems that the next digit would be next on the stack? – Mathew Kirschbaum – 2014-11-26T13:54:32.497

Answering all your question will be tricky. It would be super easy to learn by putting ed after each character in the code. Try running 128{ed_edAedbedf{ed_ed{ed%ed}1ed?ed}ed1edbed!ed}~ – Optimizer – 2014-11-26T14:19:39.360

1Answers to particular questions : doing base 10 gives an array of base 10 converted numbers, which are the digits themselves in this case. % simply take the last two numbers (in this case) and calculate the mod. Last two numbers here are the actual number and digit (always) – Optimizer – 2014-11-26T14:23:09.783

Okay, thanks for the advice! – Mathew Kirschbaum – 2014-11-26T14:23:12.953

2

C89, 43 bytes

unsigned char d(int n, int c) {
        int a=n%10;return!n||a&&!(c%a)&&d(n/10,c);
}

C89 doesn't have a boolean type. Hope that works. Also I used a second parameter to pass a copy of the original number through the stack, but the definition can be anything. To get the correct result you just have to call the function with the same value for both parameters (d(128, 128)).

EDIT: Applied suggested edits by an anonymous user

MarcDefiant

Posted 2014-11-26T03:25:28.343

Reputation: 996

Take a look at http://codegolf.stackexchange.com/review/suggested-edits/17160 , someone gave you some golfing suggestions

– Justin – 2014-11-26T11:31:39.933

Specifically against the rules. One parameter. – edc65 – 2014-11-26T17:07:17.017

Yup, this post is actually why I decided to make that rule, as it didn't seem right that the user should do the duplication instead of the program. – Mathew Kirschbaum – 2014-11-27T02:59:40.460

I guess I'll have to add a wrapper function. Does the declaration of that function add to the byte count? – MarcDefiant – 2014-12-01T08:00:43.553

2

C / C++, 58 bytes (44 in body)

Invokes Undefined Behaviour (see comments)

int d(int i){int j=i;while(i&&!(j%(i%10)))i/=10;return!i;}

true and false are 1 and 0, but feel free to add one character to the signature to return a bool.

And for fun, a recursive version which is smaller if you allow calls of the form r(128,128)

Edit: Now disallowed by the rules:

C / C++, 53 bytes (33 in body)

int r(int i,int j){return!i||!(j%(i%10))&&r(i/10,j);}

etheranger

Posted 2014-11-26T03:25:28.343

Reputation: 121

2#1 dies with a floating point exception for numbers containing a 0 because j%(i%10) will be illegal for i%10 = 0. – SBI – 2014-11-26T10:03:50.270

A floating point exception? Weird. It works perfectly on my compiler but you're right, it's undefined behaviour. Not sure what the general PCG stance on compiler-dependent UB is. – etheranger – 2014-11-26T23:33:18.790

What's "compiler-dependent UB"? Either it's UB or it isn't (and division by zero, or rather modulo zero, is indeed UB). UB shouldn't be allowed because literally anything could happen. We may assume your program will run on a machine that will blow up and kill everyone around it when a division by zero happens. Now, I'm sure you want us all to live... C does have a concept of implementation-defined behavior, but dividing by zero doesn't fall under that. – Jeroen Mostert – 2014-11-27T11:57:41.290

2

@etheranger: Division by 0 is called floating point exception for historical reason: http://stackoverflow.com/questions/16928942/why-does-integer-division-by-zero-result-in-a-floating-point-exception

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-11-27T16:29:28.037

2@JeroenMostert: I'd say over 90 % of all C answers on this site invoke UB. As long as it works with some compiler on some machine, the answer is considered valid. – Dennis – 2014-11-28T13:53:17.167

@etheranger: What compiler did you use? – Dennis – 2014-11-28T13:53:57.413

@sudo: then I'd say the C golfers need more discipline. It's one thing to have a clever hack that only works on the Foobar Bletchley because only that has programmable degaussing coils, and another to do something that renders your entire program susceptible to irreversible mangling by an optimizing compiler. That said, I suppose this sorts itself out by voting and setting appropriate rules in the question (and if all else fails, ignoring pundits like me :-)). – Jeroen Mostert – 2014-11-28T14:39:27.700

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Neat, nice history lesson :D – etheranger – 2014-12-01T04:52:43.133

@sudo Green Hills for ARM - kind of niche, I know.
@ JeroenMostert I meant the results were compiler/cpu dependent, not the defined-ness. And I would tend to agree with avoiding it - terrible practice for anywhere but PCG and I wouldn't have posted in the first place if I'd noticed. I'm leaving it as-is for now given how unimportant the content of the answer actually is.
– etheranger – 2014-12-01T04:58:43.883

2

CJam, 15 bytes

{_Abf{_g{%}*}:|!}

This is a block, the closest thing to a function in CJam. I'm only counting the body (i.e. omitting the braces). You can use it as follows:

128{_Abf{_g{%}*}:|!}~

Or if you want to test a series of inputs, you can do

[128 12 120 122 13 32 22 42 212 213 162 204]{{_Abf{_g{%}*}:|!}~}%

The block leaves 0 (falsy) or 1 (truthy) on the stack to indicate the result. (CJam doesn't have a Boolean type.)

Test it here.

Explanation:

_               "Duplicate input.";
 Ab             "Get base-10 digits.";
   f{      }    "This maps the block onto the list of digits, supplying the input each time.";
     _g         "Duplicate digit, get signum S (0 or 1).";
       { }*     "Repeat this block S times.";
        %       "Take input modulo digit.";
                "This leaves an array of zeroes for divisible digits, non-zeroes
                 for non-divisible digits, and non-zero junk for zeroes.";
            :|  "Fold OR onto this list. One could also sum the list with :+";
              ! "Logical NOT. Turns 0 into 1, and non-zero values into 0.";

Alternative, also 15 bytes

{:XAb{X\_X)?%},!}

Explanation

:X              "Store input in X.";
  Ab            "Get base-10 digits.";
    {       },  "Filter this list by the result of the block.";
     X\         "Push another copy of X, swap with digit.";
       _        "Duplicate digit.";
        X)      "Push X+1.";
          ?     "Select digit itself or X+1, depending on whether digit is 0 or not.";
           %    "Take modulo. X%(X+1) will always be nonzero for positive integers.";
              ! "Logical NOT. Turns an empty list into 1 and a non-empty list into 0.";

Martin Ender

Posted 2014-11-26T03:25:28.343

Reputation: 184 808

2

C11 - 44 Bytes in function body

Another C version, non recursive and without a floating point exception.

bool digit_multiple(int i)
{
    for(int n=i;i%10&&n%(i%10)<1;i/=10);return!i;
}

This will also work in C++, Java, and most other C-like languages.

Edited to include the improvement of primo's comment.

SBI

Posted 2014-11-26T03:25:28.343

Reputation: 211

1A version that compiles in Java (1.7.0_45-b18): int n=i;for(;i%10>0&&n%(i%10)<1;i/=10);return i<1;, one byte shorter than the OP's code. – primo – 2014-11-27T08:25:17.687

2

Julia 32 25 23

Improved using digits

Also fixes problem with negative numbers

selfDivides(x)=sum(x%digits(x).^1.)==0

Old method

All digits divide if the sum of all the remainders is 0. Like others, has a problem with negative numbers.

selfDivides(x)=sum(x.%(Float64["$x"...]-48))==0

Output

[selfDivides(x) for x in [128,12,120,122,13,32,22,42,212,213,162,204]]
12-element Array{Any,1}:
  true
  true
 false
  true
 false
 false
  true
 false
  true
 false
  true
 false

Improved method also handles BigInt

selfDivides(BigInt(11111111111111111111111111111111111111112))
true

however

selfDivides(BigInt(11111111111111111111111111111111111111113))
false

because

BigInt(11111111111111111111111111111111111111113) %3
1

waTeim

Posted 2014-11-26T03:25:28.343

Reputation: 141

2

R: 72 67 65

The function

f<-function(a)!(anyNA(a%%(d=as.double(strsplit(paste0(a),"")[[1]])))|sum(a%%d))

Thanks to @AlexA and @plannapus for the savings

Test run

i=c(128,12,120,122,13,32,22,42,212,213,162,204)
for(a in i){print(f(a))}
[1] TRUE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE

MickyT

Posted 2014-11-26T03:25:28.343

Reputation: 11 735

I count 70 bytes in your function body currently, not 72. But you can get it down to 67 using d=as.double(strsplit(toString(a),"")[[1]]);!(anyNA(a%%d)|sum(a%%d)). :) – Alex A. – 2015-07-07T20:07:40.077

@AlexA. Thanks. One of my first attempts wih R. Will definitely revisit:) – MickyT – 2015-07-07T21:09:48.153

@MickyT paste(a) instead of toString(a) gives the same result. – plannapus – 2015-07-09T14:03:49.303

@plannapus Thanks, neat little trick. Must remember that – MickyT – 2015-07-09T22:24:36.090

1

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.

Cinari

Posted 2014-11-26T03:25:28.343

Reputation: 81

You answer seems to fail for 297 (not divisible by 2). – Kevin Cruijssen – 2018-05-09T13:33:47.533

1

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)

Conor O'Brien

Posted 2014-11-26T03:25:28.343

Reputation: 36 228

The method signature can be whatever you want. Just count the function body. I think this is 11 bytes. – Erik the Outgolfer – 2017-11-17T18:38:52.967

@EriktheOutgolfer thanks, what an odd rule – Conor O'Brien – 2017-11-17T21:34:31.627

1

GNU Awk: 53 characters

The counted part:

for(;++i<=split($1,a,//);)r=r||!a[i]||v%a[i];return!r

The entire function:

function self_divisible(v, i, r)
{
    for (; ++i <= split($1, a, //); )
        r = r || ! a[i] || v % a[i]

    return ! r
}

As Awk has no boolean values, returns 1 tor true and 0 for false.

manatwork

Posted 2014-11-26T03:25:28.343

Reputation: 17 865

1

JavaScript (ES6) 30

Function with one numeric parameter. Using % and subtraction, no need to special case '0' because 0%0 is NaN in JavaScript.

Edit Saved 1 char thx DocMax

F=n=>[for(d of t=n+'')t-=n%d]&&t==n 

Just for fun, abusing the rule about not counting function signature, 4

Check=(n,t=n+'',q=[for(d of t)n-=t%d])=>t==n

Test In FireFox/FireBug console

console.log([128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204]
.map(x=>+x + ' -> ' + F(x)).join('\n'))

Output

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

edc65

Posted 2014-11-26T03:25:28.343

Reputation: 31 086

I'm going to say no to inputting a string. – Mathew Kirschbaum – 2014-11-26T17:44:48.050

1The Firefox console is happy with the replacement of of(t=n+'') with just of t=n+'' to save 1. – DocMax – 2014-11-26T22:05:55.113

1

PHP: 85 bytes (64 bytes on the body)

For this function to work, simply pass a string or a number.

0 will correctly return false.

The code:

function f($n,$i=0){for($n.='';$n[$i]&&$t=!($n%$n[$i++]););return$t&&$i==strlen($n);}

Please, DO NOT SET THE 2ND PARAMETER!

Javascript: 76 bytes (61 bytes on the body)

This is a rewrite of the previous function.

Not much changed between both versions.

Here is the code:

function f(n){for(i=0,n+='';n[i]/1&&(t=!(n%n[i++])););return t&&i==n.length}

Polyglot: Javascript+PHP 187 217 bytes (76 84 bytes without boilerplate):

Why I made it?

Because of reason and maybe because I can!

Just ignore the error on PHP: it works anyway!
No longer needed, this was fixed by removing 3 bytes.

Here is the masterpiece:

if('\0'=="\0"){function strlen($s){return $s['length'];}}
function toString(){return'';}
function f($n){for($i=0,$n=$n.toString();$n[$i]/1&&($t=!($n%$n[$i++])););return $t&&$i==strlen($n);}

You can run this code both on your console and on a PHP interpreter!


Old version:

if('\0'=="\0"){function strlen($s){return $s['length'];}}
function s($s){return('\0'=="\0")?$s+'':str_replace('','',$s);}
function f($n,$i){for($i=0,$n=s($n);$n[$i]/1&&($t=!($n%$n[$i++])););return $t&&$i==strlen($n);}

Ismael Miguel

Posted 2014-11-26T03:25:28.343

Reputation: 6 797

"and only passes in one numeric parameter". Without this you can eval($x) and pass whole code in $x – abc667 – 2015-01-01T11:35:41.137

@abc667 Sorry, but I don't get it. – Ismael Miguel – 2015-01-01T14:11:22.990

1

Octave, 33 (39 including function setup)

Using numeric-to-matrix conversion:

f=@(a)sum(mod(a./(num2str(a)-48),1))==0

Divide number elementwise by matrix X, where X is made by converting number to string and subtracting 48 to go from ASCII values to numbers again. Take modulo 1 to get decimal part of each division, confirm that all of these are zero (if any are NaN because of /0, the sum will be NaN and hence not zero).

Sample input using www.octave-online.net:

f=@(a)sum(mod(a./(num2str(a)-48),1))==0
for j=[128,12,120,122,13,32,22,42,212,213,162,204]
f(j)
end

Output:

ans =  1
ans =  1
ans = 0
ans =  1
ans = 0
ans = 0
ans =  1
ans = 0
ans =  1
ans = 0
ans =  1
ans = 0

Jørgen

Posted 2014-11-26T03:25:28.343

Reputation: 231

How can we test this? – Ismael Miguel – 2014-11-28T13:40:18.100

http://octave-online.net/ - enter the code definition from above and then (for example) f(128). Will add output – Jørgen – 2014-11-28T13:55:19.573

I had found the compiler and tried it before asking. But it seems to work fine (except for f(123), which is divisible by 1, 2 and 3). But it does work for the test-cases provided. – Ismael Miguel – 2014-11-28T14:12:23.733

1

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

JPMC

Posted 2014-11-26T03:25:28.343

Reputation: 161

1

MATLAB - 39 characters

function [b] = dividesSelf(i)
b=all(~mod(i,sscanf(num2str(i),'%1d')))
end

Bastian35022

Posted 2014-11-26T03:25:28.343

Reputation: 111

1

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

Brian

Posted 2014-11-26T03:25:28.343

Reputation: 19

1

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

Qwertiy

Posted 2014-11-26T03:25:28.343

Reputation: 2 697

The f= does not count towards the bytecount, since it's not a recursive function. This is actually 33 bytes. – Patrick Roberts – 2017-12-18T09:30:29.027

@PatrickRoberts, thanks, updated. – Qwertiy – 2017-12-18T09:54:41.977

@Optimizer I've updated language name, sorry for dissonance. – Qwertiy – 2014-12-03T11:30:40.560

JavaScript, ES6 would be the best choice :) – Optimizer – 2014-12-03T11:34:54.667

@Optimizer Ok :) – Qwertiy – 2014-12-03T11:38:15.677

1

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

Zach

Posted 2014-11-26T03:25:28.343

Reputation: 11

"and only passes in one numeric parameter" – abc667 – 2015-01-01T11:36:11.890

0

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

streetster

Posted 2014-11-26T03:25:28.343

Reputation: 3 635

0

PHP, 44 bytes

function f($n,$s=str_split){
    foreach($s($n)as$d)$f|=!$d||$n%$d;return!$f;
}

Try it online.

Titus

Posted 2014-11-26T03:25:28.343

Reputation: 13 814

0

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.

Erik the Outgolfer

Posted 2014-11-26T03:25:28.343

Reputation: 38 134

0

Python 2: 36 38 Bytes

Excluding f=lambda n:

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

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

Backerupper

Posted 2014-11-26T03:25:28.343

Reputation: 41

1all(n%(int(a)or~-n)<1for a in`n`) saves a few bytes. – Dennis – 2017-12-18T14:58:46.030

0

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.

Bolce Bussiere

Posted 2014-11-26T03:25:28.343

Reputation: 970

0

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.

TessellatingHeckler

Posted 2014-11-26T03:25:28.343

Reputation: 2 412

0

J (16)

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

Returns 0 when true, another number otherwise

ɐɔıʇǝɥʇuʎs

Posted 2014-11-26T03:25:28.343

Reputation: 4 449

0

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

cornelb

Posted 2014-11-26T03:25:28.343

Reputation: 101

You could golf it to $x=1;foreach(str_split($n)as$i)$x&=$i&&$n%$i==0;return(bool)$x; – abc667 – 2015-01-01T11:50:24.457

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 – 2014-11-26T22:16:01.697

0

Mathematica, 53 bytes (46 byte body)

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

jcai

Posted 2014-11-26T03:25:28.343

Reputation: 973

1f@x_ := Tr[x~Mod~IntegerDigits[x]] == 0 – Dr. belisarius – 2014-11-27T17:39:44.793

0

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;

Steve Robbins

Posted 2014-11-26T03:25:28.343

Reputation: 183

You can reduce this code further echo 0;exit; can simply be die('0'); – Hanky Panky – 2014-11-27T09:27:33.543

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 – 2014-11-27T17:35:37.463

0

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.

Zaq

Posted 2014-11-26T03:25:28.343

Reputation: 1 525

0

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.

Beta Decay

Posted 2014-11-26T03:25:28.343

Reputation: 21 478

1i>"0" Lexicographical comparisons are your friend :) – FryAmTheEggman – 2014-11-27T20:19:10.783

@FryAmTheEggman Great, thanks! – Beta Decay – 2014-11-27T20:21:20.033

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 – 2014-11-27T20:27:02.397

I mean j%int(i)<1 >_< – FryAmTheEggman – 2014-11-27T20:35:51.887

0

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

bacchusbeale

Posted 2014-11-26T03:25:28.343

Reputation: 1 235

All ==0 can be shortened to <1. (i==0)?false: can be replaced by (i>0)&&. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-11-28T12:03:05.470

(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̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-11-28T12:26:26.927

0

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

unclemeat

Posted 2014-11-26T03:25:28.343

Reputation: 2 302

0

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.

Roy van Rijn

Posted 2014-11-26T03:25:28.343

Reputation: 1 082

0

Scala, 38 characters

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

Jacob

Posted 2014-11-26T03:25:28.343

Reputation: 1 582

0

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.

Isiah Meadows

Posted 2014-11-26T03:25:28.343

Reputation: 1 546

0

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

fredrik

Posted 2014-11-26T03:25:28.343

Reputation: 101

0

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

pgy

Posted 2014-11-26T03:25:28.343

Reputation: 830

0

Clojure, 71 bytes

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

marctrem

Posted 2014-11-26T03:25:28.343

Reputation: 151

0

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

globby

Posted 2014-11-26T03:25:28.343

Reputation: 1 132

0

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}

Jamie

Posted 2014-11-26T03:25:28.343

Reputation: 166

>

  • Sorry for that. 2. I don't see the problem here. Can you please explain? 3. Ok, I'll recalculate.
  • < – Jamie – 2015-07-09T01:21:59.333

    Why dud you roll back your edit? – Dennis – 2015-07-09T04:06:53.973

    0

    Javascript, 82 81 80 bytes

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

    SuperJedi224

    Posted 2014-11-26T03:25:28.343

    Reputation: 11 342

    0

    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
    

    plannapus

    Posted 2014-11-26T03:25:28.343

    Reputation: 8 610

    0

    TI-BASIC, 29

    Adapted from my answer to Generate Monday Numbers.

    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.

    lirtosiast

    Posted 2014-11-26T03:25:28.343

    Reputation: 20 331

    0

    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

    Jacob Misirian

    Posted 2014-11-26T03:25:28.343

    Reputation: 737

    -1

    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.

    TheNumberOne

    Posted 2014-11-26T03:25:28.343

    Reputation: 10 855

    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. – Mathew Kirschbaum – 2014-11-27T02:56:30.557

    1

    According to http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2, 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.

    – TheNumberOne – 2014-11-27T22:19:04.010

    -1

    Mathematica - 93ish characters

    Robert G Wilson v gives us the following for Mathematica:

    Function definition:

    fQ[n_] :=
      Block[{id = Union[IntegerDigits[n]]},
       Union[IntegerQ[#] & /@ (n/id)] == {True}];
    

    To call:

    Select[Range[487], fQ[#] &]
    

    Output (ignoring divide by zero complaints):

    {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22, 24, 33, 36, 44, 48, 55, 
    66, 77, 88, 99, 111, 112, 115, 122, 124, 126, 128, 132, 135, 144, 
    155, 162, 168, 175, 184, 212, 216, 222, 224, 244, 248, 264, 288, 312, 
    315, 324, 333, 336, 366, 384, 396, 412, 424, 432, 444, 448}
    

    Slaughterteddy

    Posted 2014-11-26T03:25:28.343

    Reputation: 1

    Converting to Community Wiki, as this is not your own work. – Doorknob – 2015-07-08T11:43:55.300

    Oh, dear, the hallway monitor police are out. I gave full full credit, but I've broken some mysterious "rule" and so get castigated. This is precisely why I've given up even trying to contribute to StackExchange: aside from the privileged core who got in early, they just look down their noses at anyone new. Thanks for the -1. – Slaughterteddy – 2019-05-02T08:54:07.300

    3How can you have -ish on a character count? – Beta Decay – 2014-12-03T19:26:38.010

    -1

    Scala (56 chars: 21 for header and 35 for body)

    def f(n:Int):Boolean=n==0||n%10!=0&&n%(n%10)==0&&f(n/10)
    

    Old (81):

    def f(n:Int):Boolean=if(n==0)true else if(n%10==0)false else n%(n%10)==0&&f(n/10)
    

    bb94

    Posted 2014-11-26T03:25:28.343

    Reputation: 1 831

    error: recursive method f needs result type – Jacob – 2014-12-03T19:00:08.507