[Question]
  [
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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
  
[Answer]
# Python 2, 28 bytes
```
lambda n:'6'*len(`-~n*3/11`)
```
[Answer]
# 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.‚Äù
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
;I‚âú+{6}·µê
```
[Try it online!](https://tio.run/nexus/brachylog2#@2/t@ahzjna1We3DrRP@/7e0tPwfBQA "Brachylog ‚Äì TIO Nexus")
### 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
```
[Answer]
# Java 7, ~~96~~ ~~93~~ 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](https://codegolf.stackexchange.com/a/121851/52210).
[Try it here.](https://tio.run/nexus/java-openjdk#hY7BDoIwDIbvPkXDaVMDTCKGLPMNOHE0HhDRLGGFbENjCM@OBDzbXpr2//r3r5rSOciHqfBW4xMqptED8uE3WxUE8tFahlslRJRIPAtpdyrdY6REzKWtfW8RrBwngK6/NboC50s/t1er72BKjWw1u1yh5MMG5srBgAKs35AzLpdV8XG@NmHb@7Cbad8gM2HFBP@vHwg9IfSUuj9SAOlwIgARx@QPOgUVIyWJLMvopGTWbKkVGjfj9AU)
I guess my **66**-byte-count is a demon as well. ;)  
(Not the shortest Java answer btw, see [*@JollyJoker*'s answer for that](https://codegolf.stackexchange.com/a/122030/52210) instead.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
·∫Üa6·∏å·∫°√ê·πÇ‚Å∏·π™
```
A monadic link.
**[Try it online!](https://tio.run/nexus/jelly#ARwA4///4bqGYTbhuIzhuqHDkOG5guKBuOG5qv///zM2 "Jelly ‚Äì TIO Nexus")** - 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],[3],[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],[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](https://tio.run/nexus/jelly#ASAA3///4bqGYTbhuIzigqzhuqHDkOG5guKBuOG5qv///zM2Ng)), 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).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
RD6·πÅ·∏å·∫°√ê·πÇ¬π·π™
```
[Try it online!](https://tio.run/nexus/jelly#@x/kYvZwZ@PDHT0Pdy08POHhzqZDOx/uXPX/6J7D7Y@a1rj//2@oo2Cko2Cso2AGJE2BGESb6ygYGhiAOGARoJAZiLC0tAQA "Jelly ‚Äì TIO Nexus")
[Answer]
# C, 118 bytes
[**Try Online**](http://ideone.com/rWI7zA)
```
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;}
```
[Answer]
## 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
```
[Answer]
## 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. 
[Answer]
# [Templates Considered Harmful](https://github.com/feresum/tmp-lang), 118 bytes
```
Fun<Ap<Fun<If<lt<A<1>,Add<A<2>,A<3>>>,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>>>
```
[Try it online!](https://tio.run/nexus/templates#PYsxCsAwDAM/lMFpaCZh8FLw0F@ETqFkaN6f2ph2kk6cZGAd84YMeOiF/kCQOUlrVjYrKMwRyTQBOZhxzh6GIhPHI7byb4rKHPfsVOjbllPdrbw "Templates Considered Harmful ‚Äì TIO Nexus")
Ungolfed:
```
Fun<Ap<Fun<If<lt<A<1>, Add<A<2>, A<3>>>,
           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>>>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
- 1 byte thanks to Riley
```
6√ó≈íŒ£I-√Ñ}¬¨
```
[Try it online!](https://tio.run/nexus/05ab1e#@292ePrRSecWe@oebqk9tOb/f2NzAA)
The above code can have performance issues, here is a slightly more efficient version with 10 bytes: [TIO alternative](https://tio.run/nexus/05ab1e#@292eLpewbnFnrqHW2oPrfn/39LSEgA "05AB1E ‚Äì TIO Nexus")
## 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
```
[Answer]
## Mathematica, 76 bytes
```
Max[Take[LinearRecurrence[{11,-10},{0,6},IntegerLength[#]+1],-2]~Nearest~#]&
```
[Answer]
# [Neim](https://github.com/okx-code/Neim/), ~~12~~ 10 bytes (non-competing)
-1 byte thanks to steenbergh
```
ùê•ùêàŒì6Œò‚Ñù)‚ÇÅ>ùïî
```
Explanation:
```
               Implicit input: [366]
ùê•               Push the length of the input
                [3]
  ùêà             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
                [666]
                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](http://178.62.56.56/neim?code=%F0%9D%90%A5%F0%9D%90%88%CE%936%CE%98%E2%84%9D)%E2%82%81%3E%F0%9D%95%94&input=366)
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~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
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 46 bytes
```
dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+d[6]s.0=.
```
[Try it online!](https://tio.run/nexus/dc#i062r4oujC3WM7DVU0jJi1aIzfufUlwRZahraFAUl2JoqGWka6yfUlyZUxFtUKQLVGijZ6yVU6mdEm0G0fW/IMetIjal2K3ivyGXEZcxlxmXsSmXMZA05zI0MACyQDwzLjMgtrS0BIkZAAA "dc ‚Äì TIO Nexus")
```
dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+d[6]s.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
                                     d[6]s.0=.  Return 6 for x<3
```
[Answer]
## 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));
```
[Answer]
# [braingasm](https://github.com/daniero/braingasm), 15 bytes
```
;3*11/z+[6:10/]
```
Using the arithmetic from [orlp's Python solution](https://codegolf.stackexchange.com/a/121851/4372):
```
;                   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
```
[Answer]
I didn't see this question in the feed, and only stumbled over it by accident. Here's my answer anyway:
## JavaScript (ES6), 34 bytes
```
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.)
[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
```
[Answer]
# Java 8, 37 bytes
```
 n->(""+-~n*3/11).replaceAll(".","6");
```
Going by [Kevin Cruijssen's example](https://codegolf.stackexchange.com/a/122002/58251) and just returning a String. 
Do the \*3/11 trick to get the right length, then replace all with sixes.
[Answer]
# PHP, 49 Bytes
trim the character 6
```
for(;trim($x=$argn+$i,6)>"";)$i=($i<1)-$i;echo$x;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTYzs/6fll@kYV1SlJmroVJhCxbXVsnUMdO0U1Ky1lTJtNVQybQx1NRVybROTc7IV6mw/v8fAA "PHP ‚Äì TIO Nexus")
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
[Answer]
# 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!
[Answer]
# 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.
[Answer]
# Brainfuck, 315 bytes
```
,+>+++[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<+++++++++++<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>]<[-]+<[>-]>[<+>->]++++++[<+++++++++>-]<<<[-]++++++++++>[>.<[<<+>>-]<<[>[<<+<+>>>-]<<<[>>>+<<<-]>[<+>>-[<<[-]<+>>>-]<<<[>>>+<<<-]>[>-[>>>-<<<[-]]+<-]>-]>>>+<<]>>]
```
**[Run it here](https://copy.sh/brainfuck/)**. 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](https://codegolf.stackexchange.com/a/121851/34718). The algorithms used for each individual step are taken from [this page](https://esolangs.org/wiki/Brainfuck_algorithms). 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
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
6s√óŒ∑s.x
```
[Try it online!](https://tio.run/##MzBNTDJM/f/frPjw9HPbi/Uq/v83NjQyAQA "05AB1E ‚Äì 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
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
_√¨ e¬•6}cU
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=X+wgZaU2fWNV&input=ODg4)
[Answer]
# 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 :)
]