Show me the nearest demon

A demonic number is a positive integer whose decimal representation consists of only 6. The list of demonic numbers starts with 6, 66, 666, 6666.

Given a positive integer, output the nearest demonic number. If there are two, output the bigger one.

Testcases:

n   output
1   6
2   6
3   6
6   6
35  6
36  66
37  66
100 66
365 66
366 666
666 666
999 666

This is . Shortest answer in bytes wins.

• What is the maximum number we have to support? – Mr. Xcoder May 21 '17 at 6:38
• @Mr.Xcoder as large as you can support. – Leaky Nun May 21 '17 at 7:27
• @LeakyNun, while I'm not a regular if PPCG, I would say that rule isn't really great, because I can just say "I can only support up numbers to 34 because I wanted to have the shortest code" – Ferrybig May 21 '17 at 15:44
• @Ferrybig as large as you can support, so basically as large as the language limits you. – Leaky Nun May 21 '17 at 17:13
• Apparently the nearest demon is Jörg W Mittag. – user2357112 May 22 '17 at 19:14

Python 2, 28 bytes

lambda n:'6'*len(-~n*3/11)
• That's a neat solution. – Leaky Nun May 21 '17 at 3:53
• Wow that's impressive. Mine was 105 bytes using the trivial method rip. Nice! – HyperNeutrino May 21 '17 at 3:54
• Very cool. How did you come up with this algorithm? – David Z May 21 '17 at 18:53
• That's awesome. The equivalent in JS is a bit longer: x=>'6'.repeat((''+-~(x*3/11)).length) – Steve Bennett May 22 '17 at 8:41
• @DavidZ Hint: the average of 666 and 6666 is 3666. 3.6666... = 11/3. – orlp May 22 '17 at 8:57

JavaScript (ES6), 31 29 bytes

f=(x,s='6')=>x<3+s?s:f(x,s+6)

f=(x,s='6')=>x<3+s?s:f(x,s+6)

;[1,2,3,6,35,36,37,100,365,366,666,999,1000].forEach(x=>console.log(x,f(x)))

“That is why, I delight in weaknesses […] For when I am weak, then I am strong.”

• Wow, for once Javascript's type conversion is exactly what you need :) That's awesome. – Steve Bennett May 22 '17 at 8:28
• “That is why, I delight in weaknesses […] For when I am weak, then I am strong.” ~~ 2 Corinthians 12:10 – John Dvorak May 22 '17 at 14:26
• @JohnDvorak " Therefore I take pleasure in infirmities [...] for when I am weak, then am I strong." sounds better. – MustacheMoses Feb 28 '18 at 18:33

Brachylog, 8 bytes

;I≜+{6}ᵐ

Try it online!

Explanation

;I          The list [Input, I]
≜         Assign a value to I: 0, then 1, then -1, then 2, etc.
+        Sum Input with I
{6}ᵐ    All its digits must be 6

Java 7, 9693 66 bytes

String c(int n){String r="";for(n*=11/3;n>1;r+=6,n/=10);return r;}

Port of @orlp amazing Python 2 answer.

Try it here.

I guess my 66-byte-count is a demon as well. ;)
(Not the shortest Java answer btw, see @JollyJoker's answer for that instead.

• Using integer arithmetic must be shorter. – Leaky Nun May 22 '17 at 9:31
• C'mon, golf just one more byte please! :p – Olivier Grégoire May 22 '17 at 12:37
• None of your testcases is correct. – Leaky Nun May 22 '17 at 13:08
• @OlivierGrégoire Needs r="" as a bugfix anyway, so you get your wish :) – JollyJoker May 22 '17 at 13:51
• @LeakyNun Oops.. Copied the incorrect code.. the "6" should have been "". – Kevin Cruijssen May 22 '17 at 13:56

Jelly, 9 bytes

Ẇa6ḌạÐṂ⁸Ṫ

Try it online! - Almost no point in this link (see below)!

How?

In true golfer's style this is truly inefficient - it hits the 60s time out at TIO for the 365 test case! Locally this finishes in 37s.

Ẇa6ḌạÐṂ⁸Ṫ - Main link: n
Ẇ         - all sublists - this has an implicit make_range on it's input
-   so, for example, an input of 3 yields [,,,[1,2],[2,3],[1,2,3]]
-   the important things are: that it contains both a list of the length of the
-   decimal number, and a list 1 shorter; and that it's lists only contain
-   non-zero numbers and are monotonically increasing in length.
6       - literal 6
a        - and (vectorises), this changes all the values to 6s
-    so, the example above becomes [,,,[6,6],[6,6],[6,6,6]]
Ḍ      - convert to decimal (vectorises)  [ 6,  6,, 6,  66,   66,   666   ]
⁸  - link's right argument, n
ÐṂ   - filter keep those with minimal:
ạ     -   absolute difference (for 366 this keeps 66 AND 666; same goes for 3666; etc.)
Ṫ - tail - get the rightmost result (for 366 keeps 666, since it's longer)

A patch to make the same algorithm run within the 60s limit for 365 and 366 on TIO is to avoid the implicit vectorisation of with Ẇa6Ḍ€ạÐṂ⁸Ṫ (try that), however this will now seg-fault for an input of 999 (Triangle(999) is only 499,500 but each is a list of integers, making a total of Tetrahedral(999) = 166,666,500 integers, not memory efficient, at least in Python).

Jelly, 10 bytes

RD6ṁḌạÐṂ¹Ṫ

Try it online!

• Wouldn't a port be shorter? – Leaky Nun May 21 '17 at 6:09
• I tried and got 10 as well. – Dennis May 21 '17 at 6:12
• oh, is the problem that a space needs to be inserted between 11 and 6? – Leaky Nun May 21 '17 at 6:14
• Not sure how you'd put 11 and 6 next to each other; maybe I'm missing something. I got ‘×3:11Ṿ”6ṁ for string output, ‘×3:11D6ṁḌ for integer. – Dennis May 21 '17 at 12:15

C, 118 bytes

Try Online

a;b;d(n,m){return(m*6)+(n>0?d(n-1,m*10):0);}
f(n){a=d((int)log10(n)-1,1);b=d((int)log10(n),1);return(n-a<(b-a)/2)?a:b;}

JavaScript (ES6), 41 bytes

f=(n,i=0,j=6)=>n*2<j?i||6:f(n-j,i+j,j*10)

Test cases

f=(n,i=0,j=6)=>n*2<j?i||6:f(n-j,i+j,j*10)

console.log(f(1))   // 6
console.log(f(2))   // 6
console.log(f(3))   // 6
console.log(f(6))   // 6
console.log(f(35))  // 6
console.log(f(36))  // 66
console.log(f(37))  // 66
console.log(f(100)) // 66
console.log(f(365)) // 66
console.log(f(366)) // 666
console.log(f(666)) // 666
console.log(f(999)) // 666

Mathematica, 36 Bytes

Pure function:

Max[NestList[6+10#&,6,#]~Nearest~#]&

Explanation:

NestList[6+10#&,6,#]

Iterative create a list of length equal to the input using NestList following the pattern 6+10x(previous_value) starting from the value of 6.

~Nearest~#

Then find the value in this list closest to the input.

Max[                              ]

Lastly take the maximum value from the list of nearest values.

Whilst the list length is super inefficient as mathematica can work with arbitrary precision length numbers this program is only limited by physical memory.

Templates Considered Harmful, 118 bytes

Try it online!

Ungolfed:

A<3>,
Ap<A<0>, A<1>, Mul<A<2>, I<10>>, Add<Mul<A<3>, I<10>>, I<6>>>>>,
A<1>, I<30>, I<6>>>

05AB1E, 10 9 bytes

- 1 byte thanks to Riley

6×ŒΣI-Ä}¬

Try it online!

The above code can have performance issues, here is a slightly more efficient version with 10 bytes: TIO alternative

Explanation

6×ŒΣI-Ä}¬   Main link. Argument n
6×          Push string containing '6' n times
Œ         Push substrings
Σ   }    Sort by result of code
I-Ä     Absolute difference between n
¬   Head, implicit output
• Yeah, but then it had performance issues on the last testcase. The 60 sec maximum on TIO weren't enough to run it through ): – kalsowerus May 22 '17 at 17:05
• @Riley thanks, I updated my answer :) – kalsowerus May 22 '17 at 17:24

Mathematica, 76 bytes

Max[Take[LinearRecurrence[{11,-10},{0,6},IntegerLength[#]+1],-2]~Nearest~#]&

Neim, 12 10 bytes (non-competing)

-1 byte thanks to steenbergh

𝐥𝐈Γ6Θℝ)₁>𝕔

Explanation:

Implicit input: 
𝐥               Push the length of the input

𝐈             Inclusive range
[[1, 2, 3]]
Γ            For each
ℝ         Repeat
6            6
Θ           currently looped value times
[[6, 66, 666]]
)     End for each
𝕔  Get the closest value to
₁    The first line of input...
>   ...incremented by one

Implicitly print entire stack

Unfortunately, 𝕔 will return the lower value in a list if two numbers have the same difference, so we had to add 2 bytes to account for that.

Non-competing as >, < and were added after this question was asked (and 𝐥 was fixed to work with numbers, not just lists)

Note: Will not work for numbers with a length equal to 19 or more - as they get too big for Java's longs to handle. (but this is quite a large value, and should be fine)

Try it

• Surely you can make this answer competing.... – Leaky Nun May 21 '17 at 13:44
• e.g. would it work if you replace Γ6Θℝ) with ΓΘ𝐈Γ6)𝐣)? – Leaky Nun May 21 '17 at 13:49
• @LeakyNun I'll take a look at it. – Okx May 21 '17 at 14:05
• @LeakyNun No, I don't think there's a way to make it competing, as there was a bug (now fixed) with embedded loops. – Okx May 21 '17 at 14:21
• Who downvoted, and why? – Okx May 22 '17 at 13:02

Java 8, 37 bytes

n->(""+-~n*3/11).replaceAll(".","6");

Going by Kevin Cruijssen's example and just returning a String.

Do the *3/11 trick to get the right length, then replace all with sixes.

• @LeakyNun Of course, had to add the -~ that I should have seen ten times on this page if I'd paid attention... – JollyJoker May 22 '17 at 13:17
• I count 36 bytes. Your code has an unnecessary trailing semicolon and leading space. – Esolanging Fruit Jun 4 '17 at 22:58

QBIC, 37 27 bytes

≈!@36!<=:|A=A+!6$]?_sA,2,a Instead of using Maths™ this now uses string manipulation to find the breaks in the Demonic Domains (36, 366, ...). Inspired by @eush77 's JS answer. Explanation ≈ | WHILE <condition> ! ! a numerical cast of @  the string literal A$
36          starting out as "36"
<=    is smaller than or equal to
:   cmd line argument 'a'
A=A+ 6       Add a 6 to the end of A$(36 ==> 366 ==> 3666) !$         as a string-cast
]            WEND (ends the WHIOLE loop body)
?_sA         PRINT a substring of A$n=37, A$ = 366
,2           starting at index 2                          ^
,a           running well past the end of the string      66

dc, 46 bytes

dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+ds.0=.

Try it online!

dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+ds.0=.
Z1-10r^                                      Nearest power of 10
11*2-3/                              The number in between 6ⁿ and 6ⁿ6
d          lx[0r-]s.<.                Check which side we're on
3*ly+           Get the answer for x≥3
ds.0=.  Return 6 for x<3

C#, 142 bytes

a=>{var c=(a+"").Length;return int.Parse(a<int.Parse(3+new string('6',c==1?2:(c==10?1:c)))?new string('6',c-1):new string('6',c==10?c-1:c));};

It uses the fact, that we need to jump to the next deamonic number at every 36666... In a more readable form:

var c = (a + "").Length;
return int.Parse(a < int.Parse(3 + new string('6',
c == 1 ? 2 : (c == 10 ? 1 : c)))
? new string('6', c - 1)
: new string('6', c == 10 ? c - 1 : c));
• I think using integer arithmetic instead of String can save you a lot of bytes. – Leaky Nun May 21 '17 at 10:14
• well, you can convert a number to a string in c# just by adding a string to it because it has an overloaded + operator, as shown in my 102 bytes answer.. I also don't think you need to parse it back to an int as the question just asked us to " output the nearest demonic number" – lee Feb 28 '18 at 6:04

braingasm, 15 bytes

;3*11/z+[6:10/]

Using the arithmetic from orlp's Python solution:

;                   Read an integer from stdin
3*11/              Multiply by 3 and divide by 11
z+            If result is zero, add one
[6:10/]     While not zero, print '6' and divide by 10

I didn't see this question in the feed, and only stumbled over it by accident. Here's my answer anyway:

n=>${-~n*3/11|0}.replace(/./g,6) Add 1 byte for a numeric answer. Originally based on this ungolfed ES7 answer (37 bytes, already numeric): n=>(10**(Math.log10(-~n*3/11)|0)*2-2)/3 Annoyingly OP wants 36 to be nearer to 66 than 6. Explanation: 11/3=3.666..., so dividing by this scales the ranges 7..36, 37..366 etc. to the ranges 1..9.9, 10..99.9 etc. This can be solved purely numerically by taking 2/3 of one less than the next higher power of 10, although it's golfier to truncate, convert to string, then change all the characters to the digit 6. (Although still not as golfy as that really clever recursive answer.) CJam, 25 bytes Not as slow as the Jonathan Alan's Jelly submission, but requires O(n²) memory, where n is the input number. Yeah. ri)__{)'6*i}%f-_:z_:e<#=- This is equivalent to the following Python: num = int(input()) + 1 # CJam: ri)__ demondiffs = [int("6" * (i + 1)) - num for i in range(num)] # CJam: {)'6*i}%f- absdiffs = [abs(i) for i in demondiffs] # CJam: _:z mindex = absdiffs.index(min(absdiffs)) # CJam: _:e<# print(num - demondiffs[mindex]) # CJam: =- Alternative solution, 12 bytes ri)3*B/s,'6* This is a translation of orlp's algorithm into CJam. Explanation: ri e# Read integer: | 36 ) e# Increment: | 37 3* e# Multiply by 3: | 111 B/ e# Divide by 0xB (11): | 10 s e# Convert to string: | "10" , e# String length: | 2 '6 e# Push character '6': | 2 '6 * e# Repeat character: | "66" e# Implicit output: 66 PHP, 49 Bytes trim the character 6 for(;trim($x=$argn+$i,6)>"";)$i=($i<1)-$i;echo$x;

Try it online!

Instead of trim($x=$argn+$i,6)>"" you can use a Regex solution !preg_match("#^6+$#",$x=$argn+$i) +11 Bytes or a string length equal to count 6 comparision strlen($x=$argn+$i)-strspn(\$x,6) +10 Bytes

LOLCODE 1.4, 471 bytes

HAI 1.4
CAN HAS STRING?
I HAS A i
GIMMEH i
I HAS A l ITZ I IZ STRING'Z LEN YR i MKAY
I HAS A s ITZ "3"
IM IN YR a
BOTH SAEM I IZ STRING'Z LEN YR s MKAY AN l
O RLY?
YA RLY
GTFO
OIC
s R SMOOSH s AN 6
IM OUTTA YR l
I HAS A o
DIFFRINT i AN BIGGR of i AN 4
O RLY?
YA RLY
VISIBLE 6
NO WAI
BOTH SAEM i AN SMALLR of i AN s
O RLY?
YA RLY
o R DIFF OF l AN 1
NO WAI
o R l
OIC
I HAS A f
IM IN YR b UPPIN YR k TIL BOTH SAEM k AN o
f R SMOOSH f AN 6
IM OUTTA YR b
VISIBLE f
OIC
KTHXBYE

Wow. Here's that Ungolfed and Explained:

HAI 1.4
CAN HAS STRING?
I HAS A input
GIMMEH input
I HAS A length ITZ I IZ STRING'Z LEN YR input MKAY BTW this is using the length function of the STRING library.
I HAS A sixes ITZ "3" BTW the average of for example [6...] and 6[6...] is 3[6...].
IM IN YR foreverloop BTW this loop fills the sixes variable.
BOTH SAEM I IZ STRING'Z LEN YR sixes MKAY AN length # In LOLCODE, a statement containing only an expression assigns the implicit variable IT.
O RLY? # Tests the current value in IT.
YA RLY
GTFO
OIC
sixes R SMOOSH sixes AN 6 BTW SMOOSH automatically casts things to YARN. It also does not need a MKAY unless there's something after it on the line.
IM OUTTA YR foreverloop
I HAS A outputlength
DIFFRINT input AN BIGGR of input AN 4 BTW LOLCODE doesn't have a built-in inequality operator. This just means input < 4
O RLY?
YA RLY
VISIBLE 6 BTW If it's less than 4, the algorithm of comparing to the nearest 3.6*10^n.
NO WAI
BOTH SAEM input AN SMALLR of input AN sixes BTW input<=sixes
O RLY? BTW This if statement makes sure that if the input is less than 3.6*10^length, it goes to the previous place value's demon number.
YA RLY
outputlength R DIFF OF length AN 1
NO WAI
outputlength R length
OIC
I HAS A final
IM IN YR forloop UPPIN YR iterator TIL BOTH SAEM iterator and outputlength
final R SMOOSH final AN 6
IM OUTTA YR forloop
VISIBLE final
OIC
KTHXBYE

Still wow. Here's some pseudojavascrython for you.

hello()
import string
var i
i=input()
var l=string.len(i)
var s="3"
while True:
if(string.len(s)==l):
break
s=s+6
var o
if(i!=max(i,4)): # Basically if(i<4)
print 6
else:
if(i==min(i,s)): # Basically if(i<=s)
o=l-1
else:
o=l
var f
for(var k=0;k<o;k++):
f=f+6
print(f)
exit()

Still don't get it? This program basically just (excluding inputs 1-3) compares the input to the 3.6*10^n, n being the length of the input. If it is smaller than that number, it prints the number of 6s one less than the length. If it is greater than or equal to that number, the number of sixes is the current length.

Would love some help golfing!

Haxe, 70 bytes

function(x){x*=3;x/=11;do{Sys.print('6');}while((x=Std.int(x/10))>0);}

Input has to be passed as type Float despite being an integer, otherwise Haxe will complain about trying to divide an integer (yes haxe will refuse to compile if you divide an integer by anything)

Same as all the other answers. Multiply by 3, divide by 11, print 1 6 for every digit.

Brainfuck, 315 bytes

,+>+++[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<+++++++++++<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>]<[-]+<[>-]>[<+>->]++++++[<+++++++++>-]<<<[-]++++++++++>[>.<[<<+>>-]<<[>[<<+<+>>>-]<<<[>>>+<<<-]>[<+>>-[<<[-]<+>>>-]<<<[>>>+<<<-]>[>-[>>>-<<<[-]]+<-]>-]>>>+<<]>>]

Run it here. Select a cell size that can handle values of 3*(n+1), so for all of the test cases to work, select 16. Dynamic (infinite) Memory must be turned on for this to work. This allows the tape to expand to the left. To input an integer, type the input like \366 for n=366.

Ungolfed:

Uses the same algorithm as this solution. The algorithms used for each individual step are taken from this page. All algorithms used are non-wrapping, so that the program won't break for larger inputs.

,+ # n = n plus 1
>+++ # 3
[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-] # n = n*3
<+++++++++++ # 10
<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>] # n = n/10
<[-]+<[>-]>[<+>->] # if (n == 0) { n = n plus 1 }
++++++[<+++++++++>-] # '6' (54)
<<<[-]++++++++++> # 10
[ # while (n above 0)
>.< # print '6'
[<<+>>-]<<[>[<<+<+>>>-]<<<[>>>+<<<-]>[<+>>-[<<[-]<+>>>-]<<<[>>>+<<<-]>[>-[>>>-<<<[-]]+<-]>-]>>>+<<]>> # n = n/10
]
• Surely the n=n*3 can be golfed to something like [->+++<]? And the divmod algorithm to divide by 10? – Jo King Feb 28 '18 at 0:27
• 134 bytes, which could be improved further – Jo King Feb 28 '18 at 1:17
• @JoKing You have to use non-wrapping algorithms to support the larger test cases, so your solution doesn't actually work. There's a reason why I didn't use TIO. – mbomb007 Feb 28 '18 at 15:54
• Oops, I'll remove the wrapping part, which was only the number. 140 bytes (TIO because it's easier to give the code) (EOF = 0) – Jo King Feb 28 '18 at 22:41

05AB1E, 7 bytes

6s×ηs.x

Try it online!

Program # Input ====================|> 2
--------#---------------------------+--------
6s×     # Push N 6's as a string.   | 66
ηs   # Prefixes of this.         | [6, 66]
.x # Closest element to input. | 6

_ì e¥6}cU

Try it

C#, 102 bytes

string a(int j,int k=0)=>(j+"|"+(k=k==0?j:k)).Split('|').Where(s=>s.All(c=>c=='6')).Max()??a(j+1,k-1);

Kinda disappointed in the length of this, could do exactly the same as the shorter answer in Java but I did not really understand it because I am a lazy, stupid .NET developer :)