24
\$\begingroup\$

You will be given a positive, whole number (that will never contain a 0) as input. Your task is to check whether it is a Lynch-Bell number or not.

A number is a Lynch-Bell number if all of its digits are unique and the number is divisible by each of its digits.

In fact, there are actually only 548 Lynch-Bell numbers, so hard-coding is a possibility, but will almost certainly be longer.

126 is a Lynch-Bell number because all of its digits are unique, and 126 is divisible by 1, 2, and 6.

You can output any truthy and falsy value.

Examples:

7 -> truthy
126 -> truthy
54 -> falsy
55 -> falsy
3915 -> truthy

This is OEIS A115569.

\$\endgroup\$
  • 1
    \$\begingroup\$ Related. (Asks for all the numbers instead of posing a decision problem.) \$\endgroup\$ – Martin Ender Jul 4 '17 at 11:54
  • 1
    \$\begingroup\$ Can I take input as a string? \$\endgroup\$ – TheLethalCoder Jul 4 '17 at 12:38
  • 2
    \$\begingroup\$ @TheLethalCoder Of course you can, that's a silly question. \$\endgroup\$ – Okx Jul 4 '17 at 12:40
  • 7
    \$\begingroup\$ @Okx Not all challenge posters are as flexible in their allowed inputs as you so always worth an ask. \$\endgroup\$ – TheLethalCoder Jul 4 '17 at 12:41

25 Answers 25

27
\$\begingroup\$

Mathematica, 42 bytes

0!=##&@@d&&##&@@((d=IntegerDigits@#)∣#)&

I think 0!=##&@@d&&##&@@ is a new low in readability for Mathematica...

Explanation

Some of the basic syntactic sugar used here:

  • & has very low precedence and turns everything left of it into an unnamed function.
  • && is just the And operator.
  • # is the argument of the nearest enclosing unnamed function.
  • ## is a sequence of all of the function's arguments.
  • @ is prefix notation for function calls, i.e. f@x == f[x].
  • @@ is Apply, which passes the elements of a list as individual arguments to a function, i.e. f@@{a,b,c} == f[a,b,c].

With that out of the way...

(d=IntegerDigits@#)

This should be fairly self-explanatory: this gives us a list of the input's decimal digits and stores the result in d.

(...∣#)

This tests the input for divisibility by each of its digits (because the divisibility operator is Listable). This gives us a list of Trues and Falses.

...&@@...

We apply the function on the left-hand side to the list of booleans, such that each boolean is a separate argument.

...&@@d

We apply another function to d, so that the individual digits are given as separate arguments. The function is 0!=##&, i.e. Unequal[0, d1, d2, ...]. It checks that all the digits are distinct (and that they are distinct from 0 but that's given by the challenge, and if it wasn't, it wouldn't be a divisor anyway). 0!=##& is really just a 1-byte saver on using Unequal itself, and it works because there's a 1-byte element (0) that we know is not present. So this first thing checks that the digits are unique. Let's call this result U

...&&##

Again, this is really just shorthand for And[U, ##]. With ## being a sequences, the individual booleans from the initial divisibility check are expanded into the And, so we get And[U, d1∣n, d2∣n, ...] which checks that both the digits are unique and each digit divides the input.

\$\endgroup\$
  • 6
    \$\begingroup\$ ##&@@d&&##&@@? What does that even do? \$\endgroup\$ – Okx Jul 4 '17 at 12:03
  • \$\begingroup\$ @Okx Added an explanation. \$\endgroup\$ – Martin Ender Jul 4 '17 at 12:12
  • \$\begingroup\$ May be you can replace 0!= by 0< ? \$\endgroup\$ – sergiol Jul 4 '17 at 14:26
  • \$\begingroup\$ @sergiol I'd have to sort the digits to do that. \$\endgroup\$ – Martin Ender Jul 4 '17 at 14:49
  • \$\begingroup\$ New low in readability indeed, normally Mathematica looks like a bunch of syntax-sugar around a few function names I can understand, I was unaware you could make a program entirely out of the sugar :p (of course, your excellent explanation let's me see that its of course not all sugar, but still, very impressive!) \$\endgroup\$ – mbrig Jul 4 '17 at 19:13
11
\$\begingroup\$

Python 3, 56 bytes

lambda n:any(int(n)%int(x)for x in n)or len(n)>len({*n})

Try it online!

Output False if it's IS a Lynch-Bell number, True otherwise.

\$\endgroup\$
  • 1
    \$\begingroup\$ Is this inputting as a string? \$\endgroup\$ – CalculatorFeline Jul 5 '17 at 17:18
  • 2
    \$\begingroup\$ This has two problems: 1) it doesn't give truthy/falsey answers as specified (it's just 4 bytes!); 2) it throws an exception on the input "10". Otherwise, very nice and concise! \$\endgroup\$ – CR Drost Jul 5 '17 at 17:33
  • \$\begingroup\$ @CalculatorFeline Yes. \$\endgroup\$ – CR Drost Jul 5 '17 at 17:33
  • \$\begingroup\$ @CRDrost 1) the ouput well defined so there is no problem (usually) 2) there will never be 0 in the input \$\endgroup\$ – Rod Jul 5 '17 at 17:45
  • 1
    \$\begingroup\$ 1) I mean, there is a problem, which is that they asked for X and you did not give it. 2) Ah, you're totally right, I missed that completely. \$\endgroup\$ – CR Drost Jul 5 '17 at 17:55
8
\$\begingroup\$

Brachylog, 10 bytes

≠g;?z%ᵐ=h0

Try it online!

Explanation

≠             All digits are different
 g;?z         Zip the input with each of its digits
     %ᵐ       Map mod
       =      All results are equal
        h0    The first one is 0
\$\endgroup\$
6
\$\begingroup\$

C#, 87 83 bytes

using System.Linq;s=>s.Distinct().Count()==s.Length&s.All(c=>int.Parse(s)%(c-48)<1)

I wrote this in notepad before testing in Visual Studio, where it worked fine, so just realised I'm now that level of nerd...

Full/Formatted Version:

using System;
using System.Linq;

class P
{
    static void Main()
    {
        Func<string, bool> f = s => s.Distinct().Count() == s.Length
                                  & s.All(c => int.Parse(s) % (c - 48) < 1);

        Console.WriteLine(f("7"));
        Console.WriteLine(f("126"));
        Console.WriteLine(f("54"));
        Console.WriteLine(f("55"));
        Console.WriteLine(f("3915"));

        Console.ReadLine();
    }
}
\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 42 41 bytes

s=>![...s].some((e,i)=>s%e|s.search(e)<i)

Takes input as a string and returns true or false as appropriate. Edit: Saved 1 byte thanks to @RickHitchcock. Other versions:

Takes input as a string and returns 0 or 1 (i.e. logical inverse) for 40 bytes:

s=>/(.).*\1/.test(s)|[...s].some(e=>s%e)

Takes input as a number and returns 0 or 1 for 43 bytes:

n=>/(.).*\1/.test(n)|[...''+n].some(e=>n%e)

Takes input as a number and returns 1 or 0 for 45 bytes:

n=>!/(.).*\1/.test(n)&![...''+n].some(e=>n%e)
\$\endgroup\$
  • \$\begingroup\$ I was unfamiliar with the \n option for back-referencing. +1. You can move the test logic to the some method to save a byte: s=>![...s].some((e,i)=>s%e|s.search(e)<i) \$\endgroup\$ – Rick Hitchcock Jul 4 '17 at 14:09
  • \$\begingroup\$ When I used [...new Array(9999999)].map((_,n)=>n+1+"").filter(s=>![...s].some((e,i)=>s%e|s.search(e)<i)).length I got 5081 instead of the expected 548, so this is not correct as written. Really tight code, though. \$\endgroup\$ – CR Drost Jul 5 '17 at 17:25
  • \$\begingroup\$ Sorry, I retract my comment about this not being correct. My test code is not correct because the original poster expects that zeros have already been filtered out. With an extra .filter(x => x.indexOf('0')===-1) this returns 548 as promised. \$\endgroup\$ – CR Drost Jul 5 '17 at 18:01
6
\$\begingroup\$

Jelly, 6 4 bytes

Dg⁼Q

Try it online!

How it works

Dg⁼Q  Main link. Argument: n

D     Decimal; convert n to base 10.
 g    Take the GCD of each decimal digit k and n.
      For each k, this yields k if and only if k divides n evenly.
   Q  Unique; yield n's decimal digits, deduplicated.
  ⁼   Test the results to both sides for equality.
\$\endgroup\$
  • 3
    \$\begingroup\$ There's also gQV= if you prefer an ASCII-only solution. \$\endgroup\$ – Dennis Jul 4 '17 at 16:00
5
\$\begingroup\$

Python 3, 54 bytes

Returns False when a number is a Lynch-Bell number. Takes strings as input. Came up with on my own but very similar to Rod's. I would've commented under his post but I don't have any reputation yet.

lambda s:len({*s})<len(s)+any(int(s)%int(c)for c in s)

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Stephen Jul 4 '17 at 21:27
  • \$\begingroup\$ Welcome! Like Rod's, your function throws an exception on input "10". \$\endgroup\$ – CR Drost Jul 5 '17 at 17:34
  • 1
    \$\begingroup\$ @CRDrost "You will be given a positive, whole number (that will never contain a 0) as input." \$\endgroup\$ – C McAvoy Jul 5 '17 at 19:32
  • \$\begingroup\$ Right, I've posted comments everywhere else I complained about this, but I apparently missed this one. Sorry, retracted! \$\endgroup\$ – CR Drost Jul 5 '17 at 19:36
  • \$\begingroup\$ @CRDrost No worries! \$\endgroup\$ – C McAvoy Jul 5 '17 at 20:01
2
\$\begingroup\$

Jelly, 8 bytes

D⁼QaDḍ$Ạ

Try it online!

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

PHP, 62 48 bytes

while($i=$argn[$k++])$r|=$argn%$i|$$i++;echo!$r;

Run as pipe with -nR or test it online. Empty output for falsy, 1 for truthy.

breakdown

while($i=$argn[$k++])   # loop through digits
    $r|=                    # set $r to true if
        $argn%$i            # 1. number is not divisible by $i
        |$$i++;             # 2. or digit has been used before
echo!$r;                # print negated $r
\$\endgroup\$
2
\$\begingroup\$

Haskell, 61 bytes

(#)=<<show
(d:r)#n=notElem d r&&mod n(read[d])<1&&r#n
_#_=0<3

Try it online!

Defines an anonymous function (#)=<<show which, given a number, returns True or False.

\$\endgroup\$
  • \$\begingroup\$ This function fails on the input 10. \$\endgroup\$ – CR Drost Jul 5 '17 at 17:17
  • \$\begingroup\$ Sorry, I am wrong about that -- I missed that you're not required to provide any answer for inputs that have 0s in them. \$\endgroup\$ – CR Drost Jul 5 '17 at 18:02
1
\$\begingroup\$

05AB1E, 8 bytes

SÖP¹DÙQ*

Uses the 05AB1E encoding. Try it online!

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

Mathematica, 57 bytes

Tr@Boole[IntegerQ/@Union[s=#/IntegerDigits@#]]==Length@s&
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save numerous bytes if you use the builtin IsLynchBellNumber \$\endgroup\$ – Okx Jul 4 '17 at 14:53
  • 1
    \$\begingroup\$ why don't you make the same offer to Martin? \$\endgroup\$ – J42161217 Jul 4 '17 at 15:00
  • \$\begingroup\$ @Okx but it's less fun that way. \$\endgroup\$ – QBrute Jul 4 '17 at 21:57
  • \$\begingroup\$ @QBrute Can you take a joke? \$\endgroup\$ – Okx Jul 4 '17 at 22:02
  • 1
    \$\begingroup\$ @Okx It would have been more believable as LynchBellNumberQ. ;) \$\endgroup\$ – Martin Ender Jul 5 '17 at 5:20
1
\$\begingroup\$

Python 2, 66 bytes

This is a solution in Python 2, whose whole purpose is to output True for truthy and False for falsy:

lambda n:len(set(n))==len(n)and not any((int(n)%int(x)for x in n))

Try it online!

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

Haskell, 260 241 201 162 bytes

f([x])=1<2
f(x:xs)=not(x`elem`xs)&&(f xs)
r n i= n`mod`(read[(show n!!i)]::Int)==0
q n 0=r n 0 
q n i=r n i&&q n(i-1)
p n=length(show n)-1
s n=q n(p n)&&f(show n)

Explanation

f ([x]) = True                                           f function checks for                                                       
f (x:xs) = not(x `elem` xs) && (f xs)                    repeated digits              
r n i = n `mod` (read [(show n !! i)] :: Int) == 0       checks whether num is 
                                                         divisible by i digit
q n 0 = r n 0                                            checks wether n divisible
q n i = r n i && q n (i-1)                               by all of its digits                             
p n = length (show n) -                                  gets length of number                             
s n = (q n (p n)) && (f (show n))                        sums it all up!!!

Have significantly shortened thanx to Laikoni

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG and Haskell golfing in particular! This answer can be considerably shortened by removing superfluous spaces, e.g. the ones around the equal signs or next to parenthesis. \$\endgroup\$ – Laikoni Jul 5 '17 at 12:40
  • 1
    \$\begingroup\$ You might also be interested in Tips for golfing in Haskell and the Guide to Golfing Rules in Haskell. \$\endgroup\$ – Laikoni Jul 5 '17 at 12:43
  • \$\begingroup\$ @Laikoni Thanx for your advice! I'm looking into it \$\endgroup\$ – Sergii Martynenko Jr Jul 5 '17 at 13:51
1
\$\begingroup\$

Japt, 15 14 11 10 bytes

Returns true or false.

ìâ ¥Uì_myU

Test it


Explanation

Implicit input of integer U.

ìâ

Convert U to an array of digits (ì), remove the duplicates (â) from that array and convert back to an integer.

Uì_

Convert to an array of digits again, pass that array through a function (_) and convert back to an integer afterwards.

myU

Map (m) over the array, getting the GCD (y) of each digit and U. (If a number is divisible by another number then the GCD of both will be the second number).

¥

Check for equality. Implicit output of boolean result.

\$\endgroup\$
  • \$\begingroup\$ ©! -> « for -1 byte \$\endgroup\$ – Justin Mariner Sep 11 '17 at 17:35
  • \$\begingroup\$ Thanks, @JustinMariner; don't know how that went so long without being spotted! I found a shorter solution, though. \$\endgroup\$ – Shaggy Sep 11 '17 at 19:11
0
\$\begingroup\$

Neim, 9 bytes

𝐮ℚ₁𝐅₁𝕌₁ℚ𝕒

Try it online!

-2 thanks to Okx.

Hmm, there's a nice symmetry... oO.O.O.Oo

\$\endgroup\$
  • \$\begingroup\$ You can golf 𝐂D𝐮𝔼 to 𝐮ℚ (uniquify, check for equality ignoring types) \$\endgroup\$ – Okx Jul 4 '17 at 12:11
  • \$\begingroup\$ Still room for golfing there ;) \$\endgroup\$ – Okx Jul 4 '17 at 12:19
  • \$\begingroup\$ @Okx Hmm...I don't see anything particularly interesting there. \$\endgroup\$ – Erik the Outgolfer Jul 4 '17 at 12:26
0
\$\begingroup\$

Perl 6, 27 bytes

{$_%%.comb.all&&[!=] .comb}

Try it online!

  • .comb is a method which, when given no arguments, splits a string into its individual characters. A number is implicitly converted into a string, and so .comb returns its digits.
  • .comb.all is an and-junction of all of the digits.
  • $_ %% .comb.all is an and-junction of the divisibility of the input argument $_ by all of its digits. For example, if $_ is 123, the junction is all(True, False, True), which collapses to False in a truthy context.
  • [!=] .comb reduces the digits of the input argument with the != operator, which evaluates to True if the digits are all different.
\$\endgroup\$
0
\$\begingroup\$

Retina, 37 bytes

(.).*\1
0
.
<$&$*1>$_$*
<(1+)>\1+

^$

Try it online! Link includes test cases. Explanation: The first stage replaces any duplicate digit with a zero. The second stage replaces each digit with its unary representation followed by the unary representation of the original number. The third stage then computes the remainder of the division of original number by each non-zero digit. If the number is a Lynch-Bell number then this will delete everything and this is tested for by the final stage.

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

Ruby 2.4, 42 bytes

->x{(r=x.digits)|[]==r&&r.none?{|f|x%f>0}}

(No TIO yet, sorry)

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

CJam, 17 bytes

CJam is the Java of golfing languages. It's even interpreted in Java!

{_Ab__L|=@@f%:+>}

Explanation:

{   e# Stack:              3915
_   e# Duplicate:          3915 3915
Ab  e# Digits in base 10:  3915 [3 9 1 5]
__  e# Duplicate twice:    3915 [3 9 1 5] [3 9 1 5] [3 9 1 5]
L|  e# Remove duplicates:  3915 [3 9 1 5] [3 9 1 5] [3 9 1 5]
=   e# Test equality:      3915 [3 9 1 5] 1
@@  e# Rotate twice:       1 3915 [3 9 1 5]
f%  e# Modulo each:        1 [0 0 0 0]
:+  e# Sum:                1 0
>   e# Greater than:       1
}   e# Output:             1 (truthy)
\$\endgroup\$
0
\$\begingroup\$

VBScript, 177 bytes

Hey all, this is my very first CG post, and first attempt, so hope I followed all the rules...

Function L(s)
dim i,j,k,m,n
j = Len(s)
redim a(j)
n = 0
for i = 0 to j-1
   A(i) = Mid(s,i+1,1)   
   m = m + s Mod A(i)   
   if j = 1 then         
   else                             
        for k = 0 to i - 1        
            if A(i)  = A(k) then n = n + 1   
        next
   end if
next
if m + n = 0 then L = "y" else L = "n"
End Function

This can be run from Notepad by adding a line at the end

Msgbox L(InputBox(""))

And then saving it as .vbs, then double click.

Explanation:

Function L(s)                  'creates the function "L" taking test number as input
dim i,j,k,t,m,n                'variables
j = Len(s)                     '"j" gets length of test number
redim a(j)                     'creates array "a", size is length of test number 
n = 0                          'sets repeat character counter "n" to zero
for i = 0 to j-1               'for length of string
   A(i) = Mid(s,i+1,1)         'each array slot gets one test number character
   m = m + s Mod A(i)          '"m" accumulates moduli as we test divisibility of each digit
   if j = 1 then               'if test number is of length 1, it passes (do nothing)
   else                        'otherwise, gotta test for repeats     
        for k = 0 to i - 1     'for each digit already in array, test against current digit   
            if A(i)  = A(k) then n = n + 1  
                               'repeat char counter "n" stores no of repeats  
        next                   'proceed through array looking for repeat  
   end if
next                           'test next digit for divisibility and repeats
if m + n = 0 then L = "y" else L = "n"      
                               'check for any repeats and moduli,
                               'then return yes or no for LynchBelledness
End Function

VBScript is a bit of blunt instrument for golfing, but hey, I haven't learned Ruby yet...

\$\endgroup\$
  • \$\begingroup\$ Can't you remove some of the whitespace like 'L="y"' \$\endgroup\$ – Okx Jul 8 '17 at 20:01
  • \$\begingroup\$ Technically, yes! I shoulda done that...btw, i'm looking at codegolf languages that might be cool to learn, but for most, the documentation is minimal to non-existent...can anyone recommend a good language that is well documented? Was trying out "Actually/Seriously" but hit some obstacles due to lack of doc.... \$\endgroup\$ – aAaa aAaa Jul 11 '17 at 0:07
0
\$\begingroup\$

PHP, 51 bytes

prints zero for true and one for false

for(;$c=$argn[$i++];$$c=1)$t|=$$c||$argn%$c;echo$t;

Try it online!

PHP, 62 bytes

prints zero for true and one for false

for($a=$argn;$c=$a[$i];)$t|=strpos($a,$c)<+$i++||$a%$c;echo$t;

Try it online!

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

Pyth, 10 bytes

qiRQKjQT{K

Verify all the test cases.

How?

qiRQKjQT{K  ~ Full program.

     jQT    ~ The list of decimal digits of the input.
    K       ~ Assign to a variable K.
 iRQ        ~ For each decimal digit...
 i Q          ~ ... Get the greatest common divisor with the input itself.
        {K  ~ K with the duplicate elements removed.
q           ~ Is equal? Output implicitly.

Pyth, 11 bytes

&!f%sQsTQ{I

Verify all the test cases.

How?

&!f%sQsTQ{I  ~ Full program, with implicit input.

  f     Q    ~ Filter over the input string.
   %sQsT     ~ The input converted to an integer modulo the current digit.
             ~ Keeps it if it is higher than 0, and discards it otherwise.
 !           ~ Negation. If the list is empty, returns True, else False.
&        {I  ~ And is the input invariant under deduplicating? Output implicitly.
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 34 bytes

33 bytes of code + 1 for -p flag

$n=$_;$\|=$n%$_|$k{$_}++for/./g}{

Try it online!

Outputs 0 for truthy, any other number for falsy

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

Kotlin 1.1, 98 66 59 bytes

{i->i.none{i.toInt()%(it-'0')>0}&&i.length==i.toSet().size}

Beautified

{i ->
    // None of the digits are not factors
    i.none { i.toInt() % (it-'0') > 0 }
    // AND
    &&
    // None of the digits are repeated
    i.length == i.toSet().size
}

Test

var L:(String)-> Boolean =
{i->i.none{i.toInt()%(it-'0')>0}&&i.length==i.toSet().size}
data class TestData(val input: String, val output: Boolean)

fun main(args: Array<String>) {
    var inputs = listOf(
        TestData("7", true),
        TestData("126", true),
        TestData("54", false),
        TestData("55", false),
        TestData("3915", true)
    )

    for (test in inputs) {
        if (L(test.input) != test.output) {
            throw AssertionError(test.toString())
        }
    }
    println("Test Passed")
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.