# (RGS 1/5) Binary multiples [duplicate]

A binary multiple of a positive integer k is a positive integer n such that n is written only with 0s and 1s in base 10 and n is a multiple of k. For example, 111111 is a binary multiple of 3.

It is easy to show that a positive integer has infinitely many binary multiples. See here for a construction proof of one binary multiple for each k. Multiplying by powers of 10 you get infinitely many more.

Given a positive integer k, return the smallest binary multiple of k.

# Input

A positive integer k.

# Output

A positive integer n, the smallest binary multiple of k.

# Test cases

2 -> 10
3 -> 111
4 -> 100
5 -> 10
6 -> 1110
7 -> 1001
8 -> 1000
9 -> 111111111
10 -> 10
11 -> 11
12 -> 11100
13 -> 1001
14 -> 10010
15 -> 1110
16 -> 10000
17 -> 11101
18 -> 1111111110
19 -> 11001
20 -> 100
100 -> 100


This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

This is the first challenge of the RGS Golfing Showdown. If you want to participate in the competition, you have 96 hours to submit your eligible answers. Remember there is 450 reputation in prizes! (See 6 of the rules)

Otherwise, this is still a regular challenge, so enjoy!

• Related: One-zero dividend. I think this isn't a duplicate though because in that challenge all the 1's had to come before all the 0's and you didn't have to output the smallest instance.
– xnor
Feb 24, 2020 at 14:54
• @xnor thanks! Looking forward for your submission
– RGS
Feb 24, 2020 at 14:57
• This is OEIS A004290. Feb 25, 2020 at 16:39
• So which answer surprised you the most? Feb 27, 2020 at 14:08
• @a'_' ahaha incredible. Are you going to post an answer in Roj?
– RGS
Mar 1, 2020 at 11:33

# 05AB1E, 6 bytes

∞b.ΔIÖ


Try it online! or verify all test cases (courtesy of @KevinCruijssen)

## Explanation

∞b           - Infinite binary list
.Δ         - Find the first value such that..
IÖ       - It's divisible by the input

• Short answer, good job! Do you think you can add the TIO link with all the test cases?
– RGS
Feb 24, 2020 at 13:49
• @RGS Here ya go. ;) Feb 24, 2020 at 13:51
• Thanks @KevinCruijssen was going to have to go work out how to do that ;) Feb 24, 2020 at 13:51
• @ExpiredData Ah, shall I delete it so it'll be a learning curve for you? ;) Feb 24, 2020 at 13:52
• @KevinCruijssen nah I would have just gone and stolen it from another one of your answers Feb 24, 2020 at 13:53

# Python 2, 42 bytes

f=lambda k,n=0:n*(max(n)<'2')or f(k,n+k)


Try it online!

Full program, same length:

a=b=input()
while'1'<max(b):b+=a
print b


Try it online!

• Nice Python submission! If the full program is the same length and doesn't exceed the Recursion Depth, why don't you use it as the "main" submission? :)
– RGS
Feb 24, 2020 at 13:54

# MATL, 10 bytes

@YBUG\}HM


### Explanation

      % Do...while
@    %   Push iteration index (1-based)
YB   %   Convert to binary string (1 gvies '1', 2 gives '10,  etc).
U    %   Convert string to number ('10' gives 10). This is the current
%   solution candidate
G    %   Push input
\    %   Modulo. Gives 0 if the current candidate is a multiple of the
%   input, which will cause the loop to exit
}      % Finally: execute on loop exit
H    %   Push 2
M    %   Push input to the second-last normal function (U); that is,
%   the candidate that caused the loop to exit, in string form
% End (implicit). If top of the stack is 0: the loop exits.
% Otherwise: a new iteration is run
% Display (implicit)

• "Ah, why is there a bug in my program? Hm..." Feb 24, 2020 at 9:48
• I removed the bug but I don't think I fixed it :( +1!
– RGS
Feb 24, 2020 at 13:57

# JavaScript (ES6), 37 bytes

Looks for the smallest $$\n\$$ such that the decimal representation of $$\p=n\times k\$$ is made exclusively of $$\0\$$'s and $$\1\$$'s.

f=(k,p=k)=>/[2-9]/.test(p)?f(k,p+k):p


Try it online! (some test cases removed because of recursion overflow)

# JavaScript (ES6), 41 bytes

Looks for the smallest $$\n\$$ such that $$\k\$$ divides the binary representation of $$\n\$$ parsed in base $$\10\$$.

k=>(g=n=>(s=n.toString(2))%k?g(n+1):s)(1)


Try it online! (all test cases)

# PHP, 38 bytes

while(($n=decbin(++$x))%$argn);echo$n;


Try it online!

Counts up n in binary and divides it's decimal representation by k until there is no remainder; indicating the first, smallest multiple.

• Thanks for your PHP submission and thorough test case coverage! +1
– RGS
Feb 24, 2020 at 14:39

# R, 50 38 bytes

-4 bytes thanks to Giuseppe.

grep("^+$",(k=scan())*1:10^k)*k  Try it online! It follows from this blog post (linked in the question) that the smallest binary multiple of $$\k\$$ is smaller than $$\2\cdot10^{k-1}\$$; this answer uses the larger bound $$\k\cdot10^k\$$ instead. Creates a vector of all multiples of $$\k\$$ between $$\k\$$ and $$\k\cdot10^k\$$. The regexp gives the indices of those made only of 0s and 1s; select the first index and multiply by $$\k\$$ to get the answer. Will time out on TIO for input greater than 8, but with infinite memory it would work for any input. • Use grepl! 40 bytes. I came here to comment a grepl approach based on my SNOBOL answer and found your regex to be better :-) I had !grepl("^+$",F) for the record. Feb 24, 2020 at 18:38
• @Giuseppe Thanks! I knew about grepl but somehow convinced myself that it led to a longer answer... Your version is cleaner! Feb 24, 2020 at 22:07
• @Giuseppe Changed again, this time using your original regexp in another grep solution. Feb 24, 2020 at 23:45
• Quite clever! Glad I could be of assistance with that! :-) Feb 25, 2020 at 1:27

# Charcoal, 19 bytes

≔1ηＷ﹪ＩηＩθ≔⍘⊕⍘η²¦²ηη


Try it online! Link is to verbose version of code. Explanation:

≔1η


Start at 1.

Ｗ﹪ＩηＩθ


Repeat until a multiple of n is found, treating the values as base 10.

≔⍘⊕⍘η²¦²η


Convert from base 2, increment, then convert back to base 2.

η


Output the result.

# Haskell, 44 38 36 bytes

Saved two bytes by using filter as suggested by @ovs.

f k=filter(all(<'2').show)[0,k..]!!1


Try it online!

This checks all multiples of k and is slow for input 9 and 18.

I much prefer this version which defines the list of all "binary" numbers and searches for the first multiple of k among them. It quickly handles all test cases, but needs 52 bytes:

b=1:[10*x+d|x<-b,d<-[0,1]]
f k=[m|m<-b,mod m k<1]!!0


Try it online!

• 2 bytes shorter with filter.
– ovs
Feb 24, 2020 at 10:44
• @ovs Thanks, that still applies to my newer version. Somehow I always feel that list comprehension must be shorter... Feb 24, 2020 at 10:55

# T-SQL, 57 bytes

This script is really slow when using 18 as input

DECLARE @z INT = 18

DECLARE @ int=1WHILE
@z*@ like'%[^10]%'SET @+=1PRINT @z*@


# T-SQL, 124 bytes

T-SQL doesn't have binary conversion

This will execute fast:

DECLARE @ int=1,@x char(64)=0,@a int=2WHILE
@x%@z>0or @x=0SELECT
@x=left(concat(@%2,@x),@),@a-=1/~@,@=@/2-1/~@*-~@a
PRINT @x


Try it online

• I just can't seem to accept that SQL solves these challenges +1... What is the T- in T-SQL?
– RGS
Feb 24, 2020 at 14:00
• @RGS sql really is horrible for golfing, but it is the only language I know well enough to golf at this level, sql is also it is quite readable(maybe not in this case, but that is not the sql part). T stands for Transact. Feb 24, 2020 at 14:17
• maybe it wasn't clear, but I am impressed by your submissions! I wasn't trying to put you down or anything! keep up the really interesting work :D
– RGS
Feb 24, 2020 at 14:31
• @RGS not to worry, I took it as a compliment. It's cool that you post so many interesting questions. Feb 24, 2020 at 14:42
• Thanks for your feedback! I try to, at least :) See you next challenge!
– RGS
Feb 24, 2020 at 14:44

# Bash + Unix utilities, 52 bytes

for((n=1;n%$1;));do n=dc<<<2dio1d$n+p;done
echo $n  Try it online! This counts in binary, views the resulting numbers in base 10, and stops when a multiple of the input is reached. # Python 3.8 (pre-release),, 75$$\\cdots\$$ 50 52 bytes Saved 2 bytes thanks to Mukundan!!! Added 2 bytes to fix error kindly pointed out by Giuseppe. f=lambda k,n=1:(i:=int(f"{n:b}"))%k and f(k,n+1)or i  Try it online! • you can save 2 bytes by doing f'{n:b}' instead of bin(n)[2:] Try it online! Feb 24, 2020 at 11:50 • @Mukundan Clever use of f-strings - thanks! :-) Feb 24, 2020 at 11:55 # Jelly, 8 7 bytes ‘¡DṀḊƊ¿  Try it online! ### How? Note that in Jelly empty lists are falsey, while other lists are truthy. Also dequeue, Ḋ, is a monadic atom which removes the first item from a list, but when presented with only an integer Jelly will first convert that integer to a list by forming the range [1..n] thus Ḋ yields [2..n]. ‘¡DṀḊƊ¿ - Link: integer, k ¿ - while... Ɗ - ...condition: last three links as a monad: D - decimal digits e.g. 1410 -> [1,4,1,0] or 1010 -> [1,0,1,0] Ṁ - maximum 4 1 Ḋ - dequeue (implicit range of) [2,3,4] [] - (truthy) (falsey) ¡ - ...do: repeat (k times): ‘ - increment  For some reason, when the body of a while loop, ¿, is a dyad each iteration sets the left argument to the result and then sets the right argument to the value of the left argument, so the 6 byte +DṀḊƊ¿ does not work. (For example given 3 that would: test 3; perform 3+3; test 6; perform 6+3; test 9; perform 9+6; test 15; perform 15+9; etc...) Previous 8: DḂƑȧọð1#  (DḂƑ could be DỊẠ too.) DṀ+%Ịð1#  # Japt, 119 8 bytes È*nvU}a¤  Try it • Really cool solution, and it is crazy fast +1! Is it fast because of the algorithm used or because of the Japt machinery? – RGS Feb 24, 2020 at 14:01 • I think this fails for 11. Feb 25, 2020 at 9:10 • It's probably because 11 is crossed out in the program length part. – user92069 Feb 28, 2020 at 1:41 # Retina 0.8.2, 68 bytes .+$*1:1,1;
{^(1+):\1+,(.+);
$2 Td10.1*; ,0 ,10 1+,(.+)$1$*1,$1


Try it online! Somewhat slow so no test suite. Explanation:

.+
$*1:1,1;  Initialise the work area with n in unary, k in unary, and k in decimal. {^(1+):\1+,(.+);$2


If n divides k then delete everything except the result. This causes the remaining matches to fail and eventually the loop exits because it fails to achieve anything further.

Td10.1*;
,0
,10


Treat k as a binary number and increment it.

1+,(.+)
$1$*1,$1  Regenerate the unary conversion of k. # Bash + Core utilities, 40 bytes seq$1 $1$[10**$1]|grep ^*$|head -1


Try it online!

• Nice bash submission +1! Also harnessing the power of regexs, aren't you?
– RGS
Feb 24, 2020 at 14:44
• This is really nice. Is it mathematically guaranteed that the solution will be less than or equal to 10^input? Feb 28, 2020 at 14:03
• @Jonah Yes, in the question, RGS posted a link to a proof that there is always some value that works, and the proof actually yields that upper bound. Here’s the link: mathspp.com/blog/binary-multiples Feb 28, 2020 at 14:58
• @Jonah In fact, the upper bound proven is 10^input - 1 but it would take more bytes in the bash code to stop at that point. Of course, there's no harm done by producing the one extra value. Feb 28, 2020 at 15:39
• @Jonah Sorry, the upper bound proven is the number consisting of n 1s, which is even less than I had said. Feb 28, 2020 at 19:49

# W, 7 6 bytes

-1 because I realized that W has operator overloading over t.

•B⌡≡kü


Uncompressed:

*Tt!iX*


repl.it is quite slow and you need to type in the program in code.w.

## Explanation

        % For every number in the range
i   % from 1 to infinity:
X  % Find the first number that satisfies
*       %     Multiply the current item by the input
T      %     The constant for 10
t     %     Remove all digits of 1 and 0 in the current item
%     Both operands are converted to a string, just like in 05AB1E.
!    %     Negate - checks whether it contains only 1 and 0.

* % Multiply that result with the input (because it's the counter value).
$$$$

• Thanks for your W submission! I never understood why you include some code, and then right after it you say "uncompressed" and then include some other code. What does it mean?
– RGS
Feb 24, 2020 at 14:43
• The first code snippet is a compressed form of the W program, compressed in order to use up all 256 codepoints of CP437. However, there's also another non-compressed form that is human-writable (I compress my source code from on this form). The next code snippet is a human-readable non-compressed form of the W program (hence the "uncompressed"), which is part of the explanation.
– user92069
Feb 24, 2020 at 14:46
• Ok, I think I understand better now.
– RGS
Feb 24, 2020 at 14:48
• Where is the "get smallest" part? Feb 24, 2020 at 19:43
• @JonathanAllan Whoops, I forgot to add that W's behavior is different with an infinity value. Nice catch. There isn't an online interpreter with a permalink for W yet, I'm waiting for Dennis to recover.
– user92069
Feb 27, 2020 at 2:11

# Java 10, 6259 58 bytes

n->{var r=n;for(;!(r+"").matches("+");)r+=n;return r;}


Try it online.

Explanation:

n->{             // Method with long as both parameter and return-type
var r=n;       //  Result-long, starting at the input
for(;!(r+"").matches("+");)
//  Loop as long as r does NOT consists of only 0s and 1s
r+=n;        //   Increase r by the input
return r;}     //  After the loop is done, return r as result


This method above only works for binary outputs $$\\leq1111111111111111111\$$. For arbitrary large outputs - given enough time and resources - the following can be used instead (99 70 64 bytes):

n->{var r=n;for(;!(r+"").matches("+");)r=r.add(n);return r;}


Try it online.

• Isn't the reason the first code fails numeric type limitations, and doesn't everybody pretend they do not exist? Feb 24, 2020 at 13:03
• @mypronounismonicareinstate You're correct. I just figured I'd add a lambda function using java.math.BigInteger instead of int/long to prove it is possible to support an arbitrary large output if you'd want to. Feb 24, 2020 at 13:05

# Perl 5, 21 +2 (-ap) = 23 bytes

$_+=$Fwhile/[^01]/


Run with -a and -p, input to stdin. Just keeps repeatedly adding the input for as long as the result contains anything other than digits 0 and 1.

Try it online!

# Ruby, 4240 36 bytes

->k{z=k;z+=k until z.digits.max<2;z}


Try it online!

Very slow for 18, but ultimately gets the job done.

4 bytes golfed down by G B.

# C (gcc), 80 bytes

r,m,n;b(h){for(r=0,m=1;h;h/=2)r+=h%2*m,m*=10;h=r;}f(k){for(n=1;b(++n)%k;);b(n);}


This can probably be improved some but I have yet to find a way.

Converts the integer into binary and checks if it's a multiple.

Brute-force.

Try it online!

• Very clever how f() only needs to call b() (which assigns return value to parameter) rather than assign return value to parameter! Feb 24, 2020 at 19:52
• @Noodle9 I wish I could omit the double-call but div puts the result of modulo in eax (which means eax will always be 0 after the loop). Feb 24, 2020 at 19:54
• Do you mean the modulo result is in edx? Feb 27, 2020 at 3:09
• @640KB Yes. I didn't look up the docs beforehand. Feb 27, 2020 at 14:03

# Python 3, 50 48 bytes

f=lambda k,n=0:n*({*str(n)}<={*"01"})or f(k,n+k)


Try it online!

## Explanation

• n represents the current multiple of k.
• {*str(n)}<={*"01"} checks if n only contains digits 0 or 1. This is done by creating a set of characters of n, then checks if that set is a subset of $$\\{0,1\}\$$.
• n*({*str(n)}<={*"01"}) or f(k,n+k) is arranged such that the recursive call f(k,n+k) is only evaluated when n is 0 or n is not a binary multiple of k. Here multiplication acts as a logical and.

# J, 2423 22 bytes

+^:(0<10#@-.~&":])^:_~


Try it online!

Add the number to itself + while ^:...^:_ the following is true:

(0<10#@-.~&":]) - Something other than the digits 0 and 1 appear in the stringified number.

• I like your submission. Can't even tell why
– RGS
Feb 28, 2020 at 13:47

# Burlesque, 13 bytes

rimo{>]2.<}fe


Try it online!

9 & 18 do work, but take a while because they're such large multiples. So I've taken them out of tests.

ri    # Read to int
mo    # Generate infinite list of multiples
{
>]   # Largest digit
2.<  # Less than 2
}fe   # Find the first element s.t.


# Wolfram Language (Mathematica), 49 bytes

(x=#;While[Or@@(#>1&)/@IntegerDigits@x,x=x+#];x)&


Try it online!

• This fails on 11 (and, likely, 9) - the code should output the smallest binary multiple, and this one outputs the first one that has both zeroes and ones. 0-byte fix Feb 24, 2020 at 13:58
• This does not work for 3! Ping me as soon as you fix it!
– RGS
Feb 24, 2020 at 14:14
• @RGS Ping...... Feb 24, 2020 at 18:10
• @S.S.Anne thanks! My pinger is broken Feb 24, 2020 at 19:58

# MathGolf, 9 bytes

0ô+_▒╙2<▼


Try it online. (Test cases n=9 and n=18 are excluded, since they time out.)

Explanation:

0          # Start with 0
▼  # Do-while false with pop,
ô         # using the following 6 commands:
+        #  Add the (implicit) input-integer to the current value
_       #  Duplicate it
▒      #  Convert it to a list of digits
╙     #  Pop and push the maximum digit of this list
2<   #  And check if this max digit is smaller than 2 (thus 0 or 1)
# (after the do-while, the entire stack joined together is output implicitly)

• Question: if you answered 10 seconds ago, how come you already golfed it down from 10 to 9 bytes..? +1 for the mathgolf submission though
– RGS
Feb 24, 2020 at 14:45
• @RGS Yeah, could have just gone with the 9-byter, haha. I golfed it while adding the explanation (thus before posting) and realizing it could be shorter. EDIT: I've removed the strike-through 10. Feb 24, 2020 at 14:46
• If I golf my answer within the grace period then I never strike through because there's no way to recover the previous version.
– Neil
Feb 26, 2020 at 10:25

# Stax, 9 bytes

ü◘ø⌠Δ>0↔å


Port of my MathGolf answer. This is only my second Stax answer, so there might be a shorter alternative.

Explanation (of the unpacked version):

0             # Start at 0
w            # While true without popping, by using everything else as block:
c         #  Duplicate the top of the stack
E        #  Convert it to a list of digits
|M      #  Get the maximum of this list
1>    #  And check that it's larger than 1
# (after the while, the top of the stack is output implicitly as result)

• Cool Stax submission +1! Was stax created by someone from CG.SE?
– RGS
Feb 24, 2020 at 15:19
• @RGS yep, by recursive. :) Feb 24, 2020 at 16:44
• Nice! Didn't know about that meta question.
– RGS
Feb 24, 2020 at 17:20
• I'm not a really good Stax golfer. Run and debug it
– user92069
Feb 25, 2020 at 2:14
• @a'_' That unfortunately won't work for inputs that are already correct, like 1, 10, 11,100, etc. Feb 25, 2020 at 8:23

# Red, 52 bytes

func[n][i: 0 until[""= trim/with to""i: i + n"01"]i]


Try it online!

# Red, 54 bytes

func[n][i: 0 until[parse to""i: i + n[any["0"|"1"]]]i]


Try it online!

# Icon, 50 bytes

procedure f(n)
i:=seq(n,n)&0=*(i--10)
return i
end


Try it online!

seq(n,n) generates an "infinite" (seq operator doesn’t work with large integers) sequence starting at n with step n

&is conjunction - Icon evaluates the next expression and if it fails, than backtracks to the expression to its left - so generates the next integer.

i--10 finds the difference of the string representation of i with the string 10 - Icon automatically casts number to strings when an operation on strings is used.

*(1--10) finds the length of the difference of i and 10 (which is a string)

0=*(1--10) - if the length is 0, the number is composed only of 1's and 0's.

• Another uncommon language :D
– RGS
Feb 25, 2020 at 8:05
• @RGS Yes, it's true! Icon is an old language with some nice features, especially for its time. I'll write a short explanation of my code. Feb 25, 2020 at 8:07

# C# (Visual C# Interactive Compiler), 53 49 bytes

turns out Max can cast chars to codes implicitly

I tried a recursive version, but it was longer. Can't think of a way to replace the loop with LINQ...

a=>{int r=a;while(\$"{r}".Max()>49)r+=a;return r;}


Try it online!

• I don't think LINQ will be better Feb 24, 2020 at 14:10
• @ExpiredData Well, that "can't think of a way" part was implicitly followed by "without doubling the byte count" :) Feb 24, 2020 at 14:13
• It's not that far off 16 bytes more.. maybe there's a way to golf it down. Feb 24, 2020 at 14:21
• Thanks for your C# submission! What is the LINQ thing?
– RGS
Feb 24, 2020 at 14:37
• @RGS: Language INtegrated Query (LINQ) is an series of APIs in .Net that allow you to handle collections with a query language. It has two syntaxes: 1. SQL-like syntax 2. Fluent syntax on the IEnumerable<T> interface. See here for the official documentation: docs.microsoft.com/en-us/dotnet/standard/using-linq Feb 25, 2020 at 16:43

# Husk, 9 7 bytes

ḟoΛεd∫∞


Try it online!

-2 bytes from Leo.

• M*N would save you 1 byte over m*⁰N, but this can be even shorter by summing the input to itself repeatedly with ∫∞ Try it online!
– Leo
Apr 11, 2021 at 2:55
• I thought of ¡+₁, but ∫∞` is a lot smarter. Apr 11, 2021 at 4:18