text:
Find the closest three-digit hex colour
In CSS, colours can be specified by a "hex triplet" - a three byte (six digit) hexadecimal number where each byte represents the red, green, or blue components of the colour. For instance, #FF0000 is completely red, and is equivalent to rgb(255, 0, 0).
Colours can also be represented by the shorthand notation which uses three hexadecimal digits. The shorthand expands to the six digit form by duplicating each digit. For instance, #ABC becomes #AABBCC.
Since there are fewer digits in the hex shorthand, fewer colours can be represented.
The challenge
Write a program or function that takes a six digit hexadecimal colour code and outputs the closest three-digit colour code.
Here's an example:

Input hex code: #28a086
Red component

0x28 = 40 (decimal)
0x22 = 34
0x33 = 51
0x22 is closer, so the first digit of the shortened colour code is 2

Green component

0xa0 = 160
0x99 = 153
0xaa = 170
0x99 is closer, so the second digit is 9

Blue component

0x86 = 134
0x77 = 119
0x88 = 136
0x88 is closer, so the third digit is 8

The shortened colour code is #298 (which expands to #229988)

Your program or function must accept as input a six digit hexadecimal colour code prepended with # and output a three digit colour code prepended with #.
Examples

#FF0000 → #F00
#00FF00 → #0F0
#D913C4 → #D1C
#C0DD39 → #BD3
#28A086 → #298
#C0CF6F → #BC7

Scoring
This is a code-golf challenge, so shortest answer in your language wins! Standard rules apply.

"adding together the difference between each component of the full colour code and the corresponding component of the shorthand colour code" - this part is confusing. There's no adding anywhere, right?

Note that if you simply drop alternate digits then each short colour represents an equal number of full colours, so that could be considered to make a better representation than nearest colour.

Saw this in the Sandbox but forgot to mention that I don't think requiring the # adds anything to the challenge.

@GrzegorzOledzki you're right, that part is confusing. I'll go ahead an remove it because I think the example in that section is enough to explain what I mean.

May we output in lowercase?

@Arnauld yes, that's fine

0x22 is 34, not 30

@Kruga thanks, fixed

JavaScript (ES6), 55 bytes
s=>s.replace(/\w./g,x=>(('0x'+x)/17+.5|0).toString(16))

Try it online!

Nice use of toString! I didn't realize it could take a radix param.

05AB1E, 13 bytes
ćs2ôH8+17÷hJ«

Try it online!
How?
ćs2ôH8+17÷hJ« | string, S   e.g. stack: "#B23F08"
ć             | decapitate              "B23F08", "#"
 s            | swap                    "#", "B23F08"
  2           | two                     "#", "B23F08", 2
   ô          | chuncks                 "#", ["B2", "3F", "08"]
    H         | from hexadecimal        "#", [178, 63, 8]
     8        | eight                   "#", [178, 63, 8], 8
      +       | add                     "#", [186, 71, 16]
       17     | seventeen               "#", [186, 71, 16], 17
         ÷    | integer divide          "#", [10, 4, 0]
          h   | to hexadecimal          "#", ["A", "4", "0"]
           J  | join                    "#", "A40"
            « | concatenate             "#A40"
              | print top of stack

I thought about doing N 05AB1E answer too - unless I’ve missed something, hexadecimal conversion in Jelly takes quite a lot of bytes!

Yeah, no built-in for any textual base conversions in Jelly.

"ć decapitate" That's another way to describe it, lol. :D Nice answer though, +1 from me.

Japt, 16 bytes
r"%w"²_n16_r17Ãg

Try it or run all test cases
r"%w"²_n16_r17Ãg     :Implicit input of string
r                    :Replace
 "%w"                :RegEx /\w/g
     ²               :Duplicate, giving /\w\w/g
      _              :Pass each match through a function
       n16           :  Convert to decimal
          _          :  Pass through the following function, and convert back to hex
           r17       :    Round to the nearest multiple of 17
              Ã      :  End function
               g     :  Get first character

8088 Assembly, IBM PC DOS, 59 58 bytes
Unassembled listing:
BE 0082     MOV  SI, 82H    ; SI to begining of input string
AC          LODSB           ; load first '#' char into AL
B4 0E       MOV  AH, 0EH    ; BIOS display char function
CD 10       INT  10H        ; call BIOS
B3 11       MOV  BL, 17     ; set up for divide by 17
B9 0304     MOV  CX, 0304H  ; hex byte loop counter (CH=3), shift counter (CL=4)
        LOOP_BYTE:
AD          LODSW           ; load next two ASCII hex chars into AX
B7 02       MOV  BH, 2      ; hex chars loop counter
        LOOP_ALPHA:
2C 30       SUB  AL, '0'    ; convert from ASCII
3C 0A       CMP  AL, 10     ; is digit > 10 (A-F)?
7C 02       JL   NOT_ALPHA  ; if not, jump to next char
2C 07       SUB  AL, 7      ; ASCII adjust alpha char to binary
        NOT_ALPHA:
86 E0       XCHG AH, AL     ; swap first and second chars
FE CF       DEC  BH         ; decrement loop counter
75 F2       JNZ  LOOP_ALPHA ; loop to next hex char
D2 E0       SHL  AL, CL     ; shift low nibble to high nibble
02 C4       ADD  AL, AH     ; add first and second nibbles
32 E4       XOR  AH, AH     ; clear AH for add/division
05 0008     ADD  AX, 8      ; add 0.5 (8/16) to round (with overflow)
F6 F3       DIV  BL         ; divide by 17
3C 0A       CMP  AL, 10     ; is digit > 10?
7C 02       JL   DISP_CHAR  ; if not, jump to display digit
04 07       ADD  AL, 7      ; binary adjust alpha char to ASCII
        DISP_CHAR:
04 30       ADD  AL, '0'    ; convert to ASCII
B4 0E       MOV  AH, 0EH    ; BIOS display char function
CD 10       INT  10H        ; call BIOS
FE CD       DEC  CH         ; decrement loop counter
75 D4       JNZ  LOOP_BYTE  ; loop to next hex byte
C3          RET             ; return to DOS

Standalone PC DOS executable.  Input is via command line, output is to console.
Most of the code length is handling the conversion of required hex string I/O into bytes, since DOS/x86 machine code has no built-ins for that.
I/O:

Download and test HEXCLR.COM, or xxd hexdump:
0000000: be82 00ac b40e cd10 b311 b904 03ad b702  ................
0000010: 2c30 3c0a 7c02 2c07 86e0 fecf 75f2 d2e0  ,0<.|.,.....u...
0000020: 02c4 32e4 0508 00f6 f33c 0a7c 0204 0704  ..2......<.|....
0000030: 30b4 0ecd 10fe cd75 d4c3                 0......u..

Retina 0.8.2, 88 bytes
(\w)(.)
$1,$2;
[A-F]
1$&
T`L`d
\d+
$*
+`1,
,16$*
,
8$*
(1{17})*1*;
$#1;
T`d`L`1\d
B\B|;

Try it online! Link includes test cases. Explanation:
(\w)(.)
$1,$2;

Pair up the hex digits.
[A-F]
1$&
T`L`d

Convert each digit separately to decimal.
\d+
$*

Convert each decimal digit to unary.
+`1,
,16$*

Finish the hexadecimal conversion of the pair of digits.
,
8$*
(1{17})*1*;
$#1;

Add 8 and divide by 17.
T`d`L`1\d
B\B|;

Convert back to hexadecimal.

PHP, 75 67 bytes
#<?php for($m=3;$m;)echo dechex((hexdec($argn)>>--$m*8&255)/17+.5);

Try it online! or verify all test cases.

Python 3, 72 70 68 bytes
lambda x:'#'+''.join(f"{(int(x[i:i+2],16)+8)//17:X}"for i in(1,3,5))

Try it online!
This is a port of Grzegorz Oledzkis original answer, which I helped him golfing down.
Two features of Python 3 help us save bytes:

Floating point division by default
Format string literals

-2 bytes thanx to Jonathan Allan

(int(x[i:i+2],16)+8)//17 saves 2

Jelly, 20 19 bytes
ḊØHiⱮs2ḅ⁴+8:17ịØHṭḢ

Try it online!

C# (Visual C# Interactive Compiler), 81 bytes
x=>"".Aggregate("#",(a,b)=>a+$"{(Convert.ToInt32(x[b]+""+x[b+1],16)+8)/17:X}")

Try it online!

Wolfram Language (Mathematica), 63 48 bytes
"#"<>Round[15List@@RGBColor@#]~IntegerString~16&

Try it online!
-15 bytes thanks to attinat! Replacing StringJoin with <> and compressing the syntax.

RGBColor@# converts the input string to a color of the form RGBColor[r, g, b] with three floating-point arguments in the range 0..1.
Round[15 List @@ %] multiplies the list of three arguments by 15 and rounds them to the nearest integer. We now have a list of three integer values corresponding to the three desired hexadecimal digits.
%~IntegerString~16 converts this list of three integers to a list of three hexadecimal strings of one character each.
"#"<>% prepends a # character and joins all these characters together.

48 bytes

MathGolf, 19 12 bytes
╞2/¢8+F/¢'#▌

Output as character-list. If this is not allowed, an additional trailing y has to be added to join the character-list to a string.
-7 bytes thanks to @maxb, since I looked past a builtin (2ô_2<\1>] to 2/).
Try it online.
Explanation:
╞              # Remove the first character from the (implicit) input-string
 2/            # Split the string into parts of size 2
   ¢           # Convert each part from hexadecimal to integer
    8+         # Add 8 to each integer
      F/       # Integer-divide each integer by 17
        ¢      # Then convert back from integer to hexadecimal
         '#▌  '# Prepend '#' in front of the list
               # (which is output implicitly as result)

Ruby (2.5.3), 45, 44, 42 bytes
->a{a.gsub(/\w./){|b|"%X"%((8+b.hex)/17)}}

EDIT: saved one byte because we don't need a character group for the second character in the regex (inspired by Neil's answer)
EDIT 2: saved 2 bytes because the dash rocket lambda syntax doesn't need brackets around the argument

You can save 7 bytes by taking input on stdin and using the -p flag and another 2 by using $& instead of an argument inside the block: https://tio.run/##KypNqvz/P724NElDP6ZcT1@zWkk1QklVQ8NCW0VNLyO1QlPf0Fyz9v9/ZSOLRAMLs3/5BSWZ@XnF/3ULAA

@Jordan Thanks! I didn't know about either of those so that's a real help for future golfing attempts

Python 2 (109 101 97 85 83 74 bytes)
lambda x:'#'+''.join(hex(int(int(x[i:i+2],16)/17.+.5))[2:]for i in[1,3,5])

The "nearest distance" is handled by division by 17 and rounding.
Improvements:
-8 bytes by using the int(...+.5) trick instead of int(round(...))
-4 bytes by using list comprehension instead of map()
-1 byte by hardcoding # in the output (thanks @movatica)
-10 bytes by not using re.findall("..",...) in favor of explicit String splicing
-2 bytes by not using list comprehension, but an inline generator expression in join (thanks @movatica)
-1 byte by not splicing the :7 ending for blue part
-9 bytes by better iteration over colors - i.e. iterating over indices, not actual characters (thanks @movatica)

Does not run without import re. The import is required and thus adds to the bytecount!

@movatica - you're right, added it

Save 1 byte by hardcoding '#' instead of x[0].

You can skip the list comprehension inside ''.join(...), as it also handles a generator expression. Just remove the [] and save 2 more bytes :)

Nice work so far! 80 bytes: lambda x:'#'+''.join(hex(int(int(x[i:i+2],16)/17.+.5))[2:]for i in range(1,6,2))

Thanks! range(1,6,2) is even better with [1,3,5]

You're right! How could I miss that :)

Also I bet/hope there's some trick to improve the hex(...)[2:] part.

Jonathan Allen proposed a different trick for rounding in mz Pzthon3 version. It applies here as well: lambda x:'#'+''.join(hex((int(x[i:i+2],16)+8)/17)[2:]for i in[1,3,5]) -> 69 bytes

On top of @movatica's latest comment, you can additionally golf 4 more bytes: lambda x:'#'+`[hex((int(x[i:i+2],16)+8)/17)for i in 1,3,5]`[4::7]

Perl 5 -p, 35 34 bytes
@nwellnhof saved a byte
s|\w.|sprintf'%X',.5+(hex$&)/17|ge

Try it online!
Reads from STDIN, replaces each pair of items that is not # with the appropriate single character using the division by 17 method for finding the nearest, then implicitly outputs (-p) the result.

Python 3, 67 bytes
f=lambda x:(f(x[:-2])if x[3:]else"#")+f'{(int(x[-2:],16)+8)//17:X}'

Welcome. Consider adding a description, explanation, or link to an online interpreter, such as TIO where we can run your code. Code-only answers tend to get automatically flagged as low-quality. See other existing answers for examples.

R, 57 bytes
cat("#",sprintf("%x",(col2rgb(scan(,""))+8)%/%17),sep="")

Try it online!

Red, 103 bytes
func[c][r: to 1 c to #1 rejoin reverse collect[loop 3[keep to-hex/size r % 256 + 8 / 17 1 r: r / 256]]]

Try it online!
It turned out that the current Linux version of Red doesn't have an implementation of  the hex-to-rgb function, that's why I make the base conversion "manually" :)
This works fine in the Red GUI console on Windows:
Red, 94 bytes
f: func[c][r: hex-to-rgb c to #1 rejoin collect[repeat n 3[keep to-hex/size r/:n + 8 / 17 1]]]

Perl 6, 35 bytes
{S:g[\w.]=fmt :16(~$/)/17+.5: '%X'}

Try it online!

Charcoal, 22 bytes
#Ｆ⪪⮌…⮌Ｓ⁶¦²⍘÷⁺⁸⍘ι¹⁶¦¹⁷φ

Try it online! Link is to verbose version of code. Explanation:
#                       Literal `#`
      Ｓ                 Input string
     ⮌                  Reversed
    …  ⁶                Truncated to length 6
   ⮌                    Reversed
  ⪪      ²              Split into pairs of characters
 Ｆ                      Loop over each pair
               ι        Current pair
              ⍘ ¹⁶      Convert from base 16
            ⁺⁸          Add 8
           ÷       ¹⁷   Integer divide by 17
          ⍘          φ  Convert to large base
                        Implicitly print

Pyth, 20 bytes
+\#sm.H/+8id16 17c3t

Try it here.
NOTE: In case the link above raises an ImportError, go here instead; there is currently a bug in the "official" page, and this is a temporary solution by Maltysen. This link may stop working after the official one is fixed.

Forth (gforth), 87 bytes
: f d>s 1- hex ." #"3. do 2 + dup 2 s>number d>s 17 /mod swap 8 > - 1 .r loop decimal ;

Try it online!
Explanation

Ignore/truncate first character of input (#)
Set interpreter to hexadecimal mode
Output #
Loop 3 times, in each loop:

Add 2 to string starting address
Convert next 2 characters in string to a hexadecimal number
Use division and module by 17 (0x11) to get closest value for shortened component
Output with no preceding space

Set interpreter back to Decimal mode

Code Explanation
: f                    \ start a new word definition
  d>s                  \ convert double-length int to single-length (cheaper drop)
  1- hex               \ subtract 1 from string address, set current base to 10
  ." #"                \ output #
  3. do                \ start a loop from 0 to 2 (inclusive)
    2 + dup            \ add 2 to string starting address and duplicate
    2 s>number         \ parse the next 2 characters to a hexadecimal value
    d>s                \ convert result to single-length value
    17 / mod           \ get the quotient and remainder of dividing by 17
    swap               \ move the remainder to the top of the stack
    8 > -              \ if remainder is greater than 8, add 1 to quotient
    1 .r               \ output result (as hexadecimal) with no space
  loop                 \ end the loop
  decimal              \ set interpreter back to base 10 (decimal)
;                      \ end the word definition

Stax, 13 bytes
Ç┤!usτ╓♪╩⌂^÷◙

Run and debug it

K4, 39 bytes
Solution:
"#",{x@_1%17%8+16/:x?y}[.Q.nA]@/:3 2#1_

Explanation:
Uses the same strategy as a lot of these answers (i.e. add 8, divide by 17):
"#",{x@_1%17%8+16/:x?y}[.Q.nA]@/:3 2#1_ / the solution
                                     1_ / drop first character
                                 3 2#   / reshape as 3x2 (e.g. "FF", "00", "00")
                              @/:       / apply each-right to left lambda
    {                 }[     ]          / lambda with first argument populated
                        .Q.nA           / "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                   x?y                  / get index of hex character, e.g. "AA" => 10 10
               16/:                     / convert from base-16
             8+                         / add 8
          17%                           / 17 divided by...
        1%                              / 1 divided by...
       _                                / floor
     x@                                 / index into .Q.nA to get hex character
"#",                                    / prepend "#"

Extra:

"#",{x@*16\:a?&/a:abs(17*!16)-16/:x?y}[.Q.nA]@/:3 2#1_ - my original idea for 54 bytes


text:
Find the closest HTML colour name
Input
A single hex 6-digit colour code, capital letter, without #. Can also be a 24-bit integer if you prefer.
Output
The closest HTML color name (e.g red, or dark-salmon, as defined as https://www.w3schools.com/colors/colors_names.asp or see below). Distance is defined by summing the difference in red, green and blue channels.
Examples

FF04FE: magenta
FFFFFF: white
457CCB (halfway between steelblue and darkslateblue): steelblue (round up)

Rules

Standard loopholes apply.
Standard I/O applies
Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g  red = #FF0000 = 16711680 > blue = #0000FF = 256
If one hex code has two names (e.g. grey and gray), output either.
Outputs can be capitalised and hyphenated how you like
Trailing/preceding spaces/newlines are fine
You must output the names in full.
This is code-golf, so shortest answer in bytes wins.

Colors
As per suggestion in the comments, here are all of the color names with respective hex values in CSV format:
Color Name,HEX
Black,#000000
Navy,#000080
DarkBlue,#00008B
MediumBlue,#0000CD
Blue,#0000FF
DarkGreen,#006400
Green,#008000
Teal,#008080
DarkCyan,#008B8B
DeepSkyBlue,#00BFFF
DarkTurquoise,#00CED1
MediumSpringGreen,#00FA9A
Lime,#00FF00
SpringGreen,#00FF7F
Aqua,#00FFFF
Cyan,#00FFFF
MidnightBlue,#191970
DodgerBlue,#1E90FF
LightSeaGreen,#20B2AA
ForestGreen,#228B22
SeaGreen,#2E8B57
DarkSlateGray,#2F4F4F
DarkSlateGrey,#2F4F4F
LimeGreen,#32CD32
MediumSeaGreen,#3CB371
Turquoise,#40E0D0
RoyalBlue,#4169E1
SteelBlue,#4682B4
DarkSlateBlue,#483D8B
MediumTurquoise,#48D1CC
Indigo,#4B0082
DarkOliveGreen,#556B2F
CadetBlue,#5F9EA0
CornflowerBlue,#6495ED
RebeccaPurple,#663399
MediumAquaMarine,#66CDAA
DimGray,#696969
DimGrey,#696969
SlateBlue,#6A5ACD
OliveDrab,#6B8E23
SlateGray,#708090
SlateGrey,#708090
LightSlateGray,#778899
LightSlateGrey,#778899
MediumSlateBlue,#7B68EE
LawnGreen,#7CFC00
Chartreuse,#7FFF00
Aquamarine,#7FFFD4
Maroon,#800000
Purple,#800080
Olive,#808000
Gray,#808080
Grey,#808080
SkyBlue,#87CEEB
LightSkyBlue,#87CEFA
BlueViolet,#8A2BE2
DarkRed,#8B0000
DarkMagenta,#8B008B
SaddleBrown,#8B4513
DarkSeaGreen,#8FBC8F
LightGreen,#90EE90
MediumPurple,#9370DB
DarkViolet,#9400D3
PaleGreen,#98FB98
DarkOrchid,#9932CC
YellowGreen,#9ACD32
Sienna,#A0522D
Brown,#A52A2A
DarkGray,#A9A9A9
DarkGrey,#A9A9A9
LightBlue,#ADD8E6
GreenYellow,#ADFF2F
PaleTurquoise,#AFEEEE
LightSteelBlue,#B0C4DE
PowderBlue,#B0E0E6
FireBrick,#B22222
DarkGoldenRod,#B8860B
MediumOrchid,#BA55D3
RosyBrown,#BC8F8F
DarkKhaki,#BDB76B
Silver,#C0C0C0
MediumVioletRed,#C71585
IndianRed,#CD5C5C
Peru,#CD853F
Chocolate,#D2691E
Tan,#D2B48C
LightGray,#D3D3D3
LightGrey,#D3D3D3
Thistle,#D8BFD8
Orchid,#DA70D6
GoldenRod,#DAA520
PaleVioletRed,#DB7093
Crimson,#DC143C
Gainsboro,#DCDCDC
Plum,#DDA0DD
BurlyWood,#DEB887
LightCyan,#E0FFFF
Lavender,#E6E6FA
DarkSalmon,#E9967A
Violet,#EE82EE
PaleGoldenRod,#EEE8AA
LightCoral,#F08080
Khaki,#F0E68C
AliceBlue,#F0F8FF
HoneyDew,#F0FFF0
Azure,#F0FFFF
SandyBrown,#F4A460
Wheat,#F5DEB3
Beige,#F5F5DC
WhiteSmoke,#F5F5F5
MintCream,#F5FFFA
GhostWhite,#F8F8FF
Salmon,#FA8072
AntiqueWhite,#FAEBD7
Linen,#FAF0E6
LightGoldenRodYellow,#FAFAD2
OldLace,#FDF5E6
Red,#FF0000
Fuchsia,#FF00FF
Magenta,#FF00FF
DeepPink,#FF1493
OrangeRed,#FF4500
Tomato,#FF6347
HotPink,#FF69B4
Coral,#FF7F50
DarkOrange,#FF8C00
LightSalmon,#FFA07A
Orange,#FFA500
LightPink,#FFB6C1
Pink,#FFC0CB
Gold,#FFD700
PeachPuff,#FFDAB9
NavajoWhite,#FFDEAD
Moccasin,#FFE4B5
Bisque,#FFE4C4
MistyRose,#FFE4E1
BlanchedAlmond,#FFEBCD
PapayaWhip,#FFEFD5
LavenderBlush,#FFF0F5
SeaShell,#FFF5EE
Cornsilk,#FFF8DC
LemonChiffon,#FFFACD
FloralWhite,#FFFAF0
Snow,#FFFAFA
Yellow,#FFFF00
LightYellow,#FFFFE0
Ivory,#FFFFF0
White,#FFFFFF

Related (basically the opposite task)

Isn't Turquoise (#40E0D0) the closest color to #40FFEA with a sum of differences of $57$? (vs $85$ for Aqua and Aquamarine)

shouldn't round up be steelblue instead of darksleetblue?

For anyone else doing this challenge, here are the duplicated colors you can choose one of: Aqua/Cyan; DarkSlateGray/DarkSlateGrey; DimGray/DimGrey; SlateGray/SlateGrey; LightSlateGray/LightSlateGrey; Gray/Grey; DarkGray/DarkGrey; LightGray/LightGrey; Fuchsia/Magenta. I had only filtered out the duplicated grey colors, but not the other two. So I was getting off-set errors due to mismatches in my string and integer lists.. >.> Figured I'd post this here to prevent others from making the same mistake I did.

C# (Visual C# Interactive Compiler), 231+21=252 bytes
s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name

Explanation:
using System.Drawing; //System library that handles Colors in C#

C=s=>Color.FromArgb(Convert.ToInt32(s,16));        //helper method. receives a hex string and returns it's Color

f=s=>Enum.GetNames(typeof(KnownColor))             //collection of color names from the System.Drawing.KnownColor enum
         .Select(x=>Color.FromName(x))             //convert the color names to Colors
             .Where(x=>!x.IsSystemColor&x.A>254)   //filter out unwanted colors
                 .OrderBy(x=>Math.Abs(x.R-C(s).R)  //order by increasing distance
                            +Math.Abs(x.G-C(s).G)
                            +Math.Abs(x.B-C(s).B))
                     .First().Name                 //return the closest color's name

For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project Mono stating it's compatible. It works fine in VisualStudio though.
EDIT: apparently it hasn't been implemented into Tio yet!
Try it online!

C# out-golfing the golfing languages for once.  There's a first...

I'm surprised Javascript doesn't have a way to access the list but C# does

@JollyJoker This Node.js answer does import a package containing the data.

Node.js, 1488 bytes
Takes input as a 24-bit integer. Outputs in lower case.
v=>(require('zlib').inflateRawSync(Buffer('TVRbm6o4EPxLE27CowziDOiIV+bwFkkrWUPCBBg/9tdvLurZFzGX7uqqrs6Z4fr2xvHv5OYEy9uZjRC3QOjY6r/oaH4X+ugqAXiWI/P1M28AzGxQPWHuBBkB6PrbpCPmyZs+GEb5Mwrag/O9sEn7TlJ+NSnCr4TRFk7z/+25mc7l5i0lnF6bQef6Pn6tiCBXkHo12yxTpo96wCbEqfbxRUjoB7tcxfvn0fJ4POgyeoYHuEo8IafINaY59co8exT1uJ+Uq/hVsn8KUykmzDTqzin6AcD8n/nb3Sur3nDSD9cmegUf5hHlhF6F6ySOviwY/bWwi/UO1ZiA4baIj1EtJL8wcbf8gspLJJyhrnE3yo6BExUbmx3/jLjFSis4pitCW83I/SrTVyEo3uQGiEh8Rpvi80U8+OMXVrXnTnTKowf7Z7i/fFsxfOdWx9l6XjdYDhLGHrxwvvkL75fqKwRHoS3RtahFsDEl5U8TRMudBbXrVP/8UsFgcOMP4xwJBPmlsVeLr8AH7J56TAiDsxR3nmTvRulHf4LotDQJzQptlsgyeFTxeUr1bYuwT/cdZlbyoDog0wRZN5TMy3wCpgS3PCNn0VPgHM927smgBvvvwhpeCRc/7GYEOq0KE2TjZ3mkIf6avPiOLd+nVVAQvXfiTmxr/ez9QlVvJa1vaLc01K6CEeBSkLDyfcvGVulk6zcp+slU5HrZUt++NfhG0Tote8p+QXpRVtgYy1mpGZb+h3Ye5npxWKQdyDF0dnUjaqEbHZzmswHzRbl4KKmmIt+ehob2A4OgLP0HfpI5r+Lm8VEzfaEgL9jVkra94GV8uGLK+7OQArnrTcfGVo3Z4TxKNt2FICgLtwbKTPYs8hj+Ba4kCedLO0eYtYK7u31p8wdlFZrWPdFz13ZdDQpmTpgHRobc32BGa+Nc92vWCA4TgTtKEvzvKCHtMSdWPd8LonsDeEBbd3YGegUvL+4NHaBvxQ2KlvKhloBbVEXXRvSDOfOCuLClOX78hflAf0YwJ6uZmiUOvKqshM86rSvQHzUNRD2rKsP2XYu1zOcPc89c/UZ2lN/cU6jYcPWoAYnyZBAtHoRfxY0Y9DGKCsPWizbWuPqq8xlae5mqPLS222Vgdk3Wz8hEVwtdlJd8d4Drphsvl+2HeuPxP8IQ2HutUO9LTzkKyjPtFbG0Vf2flOHgcGaY1w0Qg0JQoprR4QmryG6/eTZPqd434ZuazL5RtKtEv2LKlbf8yEDFKQtdLoInB/WyKR4Gtuq5uM+tSvu1KdougpD+Cjktza30Pw','base64'))+'').replace(m=/([a-z]+)([^a-z]+)/g,(_,s,d)=>[e=0,8,16].map(x=>e+=Math.abs((v>>x&255)-(t>>x&255)),t+=parseInt(d,36))|e>m||(o=s,m=e),t=0)&&o

Try it online!
How?
The compressed string is 1683 characters long and looks like that:
"black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF"

The colors are ordered from lowest to highest value. Each color is encoded as its name in lower case followed by the difference between its value and the previous value in base-36 and in upper case:
black[0]        | 0x000000 + 0     --> 0x000000
navy[3K]        | 0x000000 + 128   --> 0x000080
darkblue[B]     | 0x000080 + 11    --> 0x00008B
mediumblue[1U]  | 0x00008B + 66    --> 0x0000CD
blue[1E]        | 0x0000CD + 50    --> 0x0000FF
darkgreen[JK1]  | 0x0000FF + 25345 --> 0x006400
green[5J4]      | 0x006400 + 7168  --> 0x008000
...             | ...
lightyellow[68] | 0xFFFF00 + 224   --> 0xFFFFE0
ivory[G]        | 0xFFFFE0 + 16    --> 0xFFFFF0
white[F]        | 0xFFFFF0 + 15    --> 0xFFFFFF

Commented
v =>                            // v = input
  ( require('zlib')             // using zlib,
    .inflateRawSync(            // inflate the
      Buffer(                   //   buffer obtained by
        'TVRbm(…)Pw',           //     converting this string
        'base64'                //     encoded in base-64
      )                         //
    ) + ''                      // and coerce it back to a string
  ).replace(                    // on which we invoke replace():
    m =                         //   initialize m to a non-numeric value
    /([a-z]+)([^a-z]+)/g,       //   for each color encoded as ...
    (_, s, d) =>                //   ... s = name, d = delta in base-36:
      [e = 0, 8, 16]            //     using x = 0 for blue, 8 for green and 16 for red,
      .map(x =>                 //     compute the error e:
        e +=                    //       add to e:
          Math.abs(             //         the absolute value of the difference between
            (v >> x & 255) -    //           the component of the target color
            (t >> x & 255)      //           and the component of the current color
          ),                    //
        t += parseInt(d, 36)    //       start by adding the delta to t
      ) | e > m ||              //     end of map(); if e is less than or equal to m:
        (o = s, m = e),         //       update o to s and m to e
    t = 0                       //   start with t = 0
  ) && o                        // end of replace(); return o

Why not compress your codes with the data string together then eval it? Had you tried this?

@tsh The JS code doesn't compress well enough to compensate for the overload induced by base64 encoding. So it would be longer. It could be rewritten to make it more deflate-friendly (e.g. by unrolling the map loop) but I doubt that would be enough.

Couldn't you generate the color names yourself? There's probably a better/faster way of doing it, but you could just brute-force it: q=i=>{b=document.createElementd;b.style.color=i;document.body.appendChild(b);h=getComputedStyle(b).color;y=h.slice(4,-1).split(",").map(e=>e.trim());return h!="rgb(36, 39, 41)"?[y.reduce((a,e)=>a+parseInt(e),0),parseInt(y.map(e=>parseInt(e).toString(16).padStart(2,"0")).join``,16)]:0};a=[];for(i=0,t="0";i<7988090793663851220822006848646;i++,t=i.toString(36)){(!t.match(/\d/g)&&q(t))?a.push([t,...q(t)]):0} (note that rgb(36, 39, 41) changes with the...

...stylesheet, this one works with StackExchange - it's just the default font color). Also, I don't know if this counts, since it would take literal days to run, but I've tested it on a small scale and can see it works (try replacing 7988090793663851220822006848646 with 39999)

Jelly, 1015 914 bytes
“¥.⁻ḲU3ŒẆȯ§.eḊC¤ŀ"}Ʋ59£Uŀ'⁶ɠıṇȥLcṆɓ?^¢Ỵɠ.ȮẆẆḊqʠu½ỊƑfĠ⁴ µ¥ɓƭÑUC½ṁUĿẆṃ⁹S/÷Ɓɗ>ṭ"»Ḳ33r64¤,Ọy“µṂFŀƲOḌẇȤạ2œxṾk,E.LẸpḄ2s⁵Ṛç¦ṆkAẋ=çw©ḌĊẒƤm`;ṄȧṄİɦbṠṆṛ⁴Ḟ[CƊėQẏƑ<:⁾Þḍ?çⱮ3ƈṗ¬!7Hẏywœ⁽Ẉ¤ṾƈpHṗ(⁾ƲḢdƲḃ'¦ṇ9ẏP¡ċ⁻ȤẒṬf§®ṬẒpJÞẒẸṪÄƊhḊḃ7ʠ%ƈėc+ġȦı©ḄO⁸ṗ:WṠß@Ä|ż_g¹Ʋ®[*ẹ5¡Ẹßė¶~[ȷ'ȧẊṖZẋ¦ẉ7Ġ⁽ė⁽ƁLP`²¶⁶* Ġv|$ṭⱮẋ_ƭø¦Ẇ-*ɓɼhCUṙƭƭƓS7Ø⁵¤³¢Ʋẉ!§ḟƇṣḟṛḳṠƬ4ẓḢTḌZżƇȦQxw}ḃçṣȮv⁷ȤĊẏyNỵʠÄ⁸hLġị³TİọȧfÞȤTO&ṡ°⁼`WẹạẇḂvðFmż]ɦo½ƓṂḟȯ#Æ⁺T)ṃç=ḣṆø⁽Wpʂqṫ&⁷¶S®¢ð:\ṚMĖḌ½⁽_ạ⁵]Xlȷg¿£⁺x0ṁo8ẒṛżøuɲẈ®§Bṡr:ċ³ḷb|Mku¬V°ḟƲ!ɦɠ4¬>ḷ^XḶɼ5[ṇƑȮ.XȮƙẎbḊÐþFæṁoOṗ⁺mṪ-&ƊṅƑḋ$!`€ɓḥƤ¡ɗbH⁻ḃÄ⁵!Ñėḅƈḳm⁴ḳcÐⱮ⁷ỤḍġḷȥṀSĖ»Ḳ
“⁸¢!İƝ\8¢[V⁸¢Ñ"ĠƙḶ-Æ⁷⁾Æ⁵¢⁸¢ƙhLṂS×®Ẓ©Aḅ¦ṚÆ&nj£ÇØ¿waþM=ÆḂḌ¢³(Ñḷx¦DẊ¢Aẓ©ḋ¬!ƁV  ṾÐẉœ¦2Ä¢⁼C®⁶ẇ£ḋṀ¤çẠÐȧIæḌH€5ẋ¥®⁹µ⁻£⁴⁸¢AƇ¢⁸¢£*ç-Ụz¬>ƈ£ʋ¢^ạṭ(ÇṪĠ¤Çŀ¬ÇḞ¢ṪĠÐCȥṖÞ¦ø}×⁹YÐƬAÇ×CÆævÇ#©ḥƙ£sVṀṙ¤ỊAÞtỤ¦AÇ¬⁶ʠ¤⁼ƈµ£ŒÞ¿§Œ÷~2~Ðɲċ×⁻¤SƤÐ}Z¦Fƙ°¹£Ḣ©£Ṁx£⁹j£Ƒs¤ɓ8¬_ḶØz°®ʂƬÐḢ@¢ẉ€¦ỴA¢Ä8gß-Ė⁸¿zṛ¤mGKÄœ>jµ\ạ¥>R¢ƤÐƤœⱮpµỴI¤Œ¤a<[Ɱa]ṠŒɲB"'(?ŀÆȦ6ȯœ|Dy¿1€ƤØ-WXßm€v¤UÐ½µẋ¦iœg€Ḥ£0-‘©ṛ®Ḣ¤⁺;$%¡3¤®Ð¿Ḋḅ249:3ÄŻ,b⁹UạN,§ʋ@€/MṪị¢

Try it online!
Thanks to @Arnauld for a suggestion that saved 41 bytes!
Full program. Takes colour as 24-bit integer as its argument and returns the colour name.
Explanation
Helper link
Colour names. Stored using compressed string, but with common words replaced by single ASCII characters in range 33 to 64
“¥...»                  | Compressed string "blue brown coral..."
      Ḳ                 | Split at spaces
       33r64¤,          | Pair the numbers 33 to 64 with these words [[33,34,35,...],["blue","brown","coral",...]]
              Ọ         | Convert the numbers to Unicode characters [["!",'"',"#",...],["blue","brown","coral",...]]
               y“µ...»  | Translate the compressed string "black navy %! ..." using the mapping generated above
                      Ḳ | Split at spaces

Main link
Stage 1: Start generating list of colour numbers. The increments between colour numbers are stored as between 1 and 3 base 249 digits. The increment has been multiplied by 3, converted to base 249 and then the number of digits minus 1 has been added to the least significant digit, before reversing the order of digits.
“⁸...‘©                | Copy compressed integers 136,1,33,198,... to register
       ṛ               | Right value (will yield value of the following):
                 ¤®Ð¿  | - While the register is non-empty, do the following, collecting values as we go:
        ®Ḣ¤            |   - Take the first value from the list held in the register, popping it from the list, x
              %¡3      |   - Repeat the following (x mod 3 times)
           ⁺;$         |     - Concatenate the first value from the list held in the register, popping it from the list
                     Ḋ | Remove the first item (will be 'None')

Stage 2: Finish generating colour numbers and look up the input
ḅ249                     | Convert from base 249 to integer
    :3                   | Integer divide by 3
      Ä                  | Cumulative sum: 128,139,205,255,25600,...
       Ż                 | Prepend zero
        ,                | Pair with input
         b⁹              | Convert to base 256: [[0],[128],[139],[205],[255],[100,0],...], [input in base 256]
           U             | Reverse order of innermost lists (so RGB becomes BGR, GB becomes BG and B remains as B); this is because colours with no red component will be a list with only two members, and colours with only blue will just have one member
                ʋ@€/     | Reduce using the following as a dyad for each; effectively calls the following once for each colour with the reversed base-256 colour as left argument and the reversed base-256 input as right
            ạ            | - Absolute difference of the colour and the output of stage 1
             N           | Negate
              ,          | - Pair with the colour
               §         |   - Sum each of these
                    M    | Indices of maximum
                     Ṫ   | Tail (will be the index of the largest colour value)
                      ị¢ | Index into helper link

Colours are reversed before comparing because colours with no red component (for example) will end up as a 2 component list.
TIO link generates 10 random colours and shows the output so will be different each time.

Input can be 24-bit. I already said standard I/O applies.

@GezaKerecsenyi Thanks. You also said it needed to be a six-digit hex string, so it would be good to clarify in the question.

Would it be shorter to encode $i\times 4+n$ (or maybe $i\times 3+n$), where $i$ is the increment and $n$ is the number of additional base-250 numbers required to fully describe it? (I think that would fit on 341 numbers instead of 392).

Here is some JS code to illustrate what I mean. (This is a fixed version with encoding + decoding. Sorry about the multiple posts.)

@Arnauld thanks. I needed up using base 249. In brief, I multiplied the increments by 3, converted to base 249, reversed the order of digits and added length-1 to the first digit. These are then encoded as Jelly characters. For decoding, I pop the first digit, then pop a further (first digit mod 3) digits and concatenation them (reversing the order in the process). I repeat until no digits are left. This is then converted back from base 249 to integer. The reason for 249 is that 250, the least significant digit isn’t necessarily a multiple of 3.

Awesome! (And BTW: in my version, I should have used mod 62, not mod 63 which generates a 250 somewhere.)

Wolfram Language (Mathematica), 164 bytes
Note: This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link.
g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}]

Defines the function g, which takes an integer as input. Test cases:
AssociationMap[g, {327581, 3483113, 2820178, 4358965,
  2058772, 13569770, 8698378, 2897368, 3896382, 12856883}]

(* <|
  327581 -> "MediumSpringGreen",
  3483113 -> "RoyalBlue",
  2820178 -> "MidnightBlue",
  4358965 -> "DarkOliveGreen",
  2058772 -> "ForestGreen",
  13569770 -> "Magenta",
  8698378 -> "Olive",
  2897368 -> "RoyalBlue",
  3896382 -> "DarkOliveGreen",
  12856883 -> "Brown"
|> *)

Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.

RebeccaPurple is new(ish) and a tribute to Eric Meyer’s daughter: https://lists.w3.org/Archives/Public/www-style/2014Jun/0312.html . I’ll raise it as a feature enhancement with Mathmatica.

JavaScript (Node.js) + color-name package, 259 279 284 259 278 282 299 312 364 bytes
c=>{w=[]
K=Object.keys
for(x in d=require('color-name')){(w[W=(p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2)+p(1)+p(0)]=w[W]||[]).push(x)}S=[]
for(s of r=w[K(w)[0]]){(S[z=(W=d[s])[0]+W[1]+W[2]]=S[z]||[]).push([d[s],s])}return S[K(S).pop()].sort().pop()[1]}

Try it online!
Commented:
c=>{w=[]                      // build dict of arrays of names, by color distance:
K=Object.keys
for(x in d=require('color-name')){
  (w[W=
      (p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2) + p(1) +p(0)
    ] = w[W]||[]).push(x)
}S=[]                         // distances were ordered by Object.keys()
for(s of r=w[K(w)[0]]){       // build dict of [[RGB, name]+] by channel sum for distance ties:
  (S[ z= (W=d[s])[0] + W[1] + W[2] ]= S[z]||[]).push([d[s],s])
} return S[ K(S).pop()        // highest channel sum
          ].sort().pop()[1]}  // [name of] highest RGB

I had to
npm install color-name

for the require() to work. I don't think I can npm install on TIO, so I hardcoded the dictionary in the header.
This package contains the same 148 entries as the w3schools page, names are lowercase.
I have no idea who created it and when, I just found it while googling. There is a Debian package for it, so I assume it's older than this question.
[Edit: third size reduction / major overhaul]
[Edit 5th/correction: that version had 282 bytes but was missing the tiebreak by RGB value. I don't think I can fix that one and then golf it smaller than this one, so I removed that code from the post.]
This time, I rewrote most of the code. I feel that it's so different from before, it doesn't make sense to keep history in the post.
@Shaggy saved me 4 bytes from the last version by omitting parentheses around single arrow function parameters. Now, there are 6 of those, so basically I owe 12 bytes of thanks.
I switched from constructing dicts/lists manually to using map and filter everywhere, which enabled/prompted a lot of restructuring. I also found some more situations where I could assign variables later.
[Edit: 4th shrinking, return to the roots]
Within a minute of dismissing history (above), I realized my mistake in saying that.
I applied the lessons learned so far to the old code, and I saw that the second sort() was pointless. So right now, that code is ahead by 4 bytes.
[Edit: 4.1th: DUH! all sorts were pointless. -19 more bytes]
[Edit: 5th iteration, growing but now (hopefully) correct]
@Lukas Lang pointed out that my code wasn't correct in cases where the channel sum was tied. I had the wrong impression that this never occurs.
To fix it, I needed to fill the arrays in S with [RGBarray, name] pairs instead of just names. This way, default array sorting completes the job.
[Edit: 6th reduction - gift from a higher realm]
@Shaggy gets all the credit for this round. .reverse()[0] is .pop(). Obviously...  Also, implicit type conversion makes ('0x'+c) work instead of parseInt(c,16). And if you get the parantheses right, EVERY variable can be assigned at first use. This time, that was W and p.

If you have a required package that’s not a standard part of the language, it needs to be in the language header at the top of your entry (i.e. JavaScript (Node.js) + color-name). This means it competes with other entries using the same package, but not directly with other JavaScript (Node.js) entries.

That makes sense. Thanks!

If an arrow function only has one parameter, it does not need to be enclosed in parentheses.

Thanks @Shaggy, that'll save me another 4 bytes!I'm starting today's iteration now, in the hope of finding some more shrinking potential

Yeah, from a cursory glance, there's a good bit you can save here.

Unless I'm mistaken, the code fails for cases where the second tie-breaking rule is needed, such as e8fcf8: both Azure and MintCream have a distance of 18 to that color, and a channel sum of 750. Thus the result should be MintCream, while this code returns Azure.

@Lukas Lang : You are not mistaken. I had written some code to see if this situation ever came up, which must have had bugs, because it said no. Fix in a minute. Thank you!

A few quick tweaks from my phone: https://tio.run/##TY6xboNAEER7vgK5iHaDQBjJUprlB6zIBQXFaoXwcZbPSThyB4YkzreTo0szxYzezNzae@uVM8OY9rbT66qo/JmJJTrS6XzTasze9JePLtbBEps@7sjpz8k43Sj7bl3TNH37oRuEmWuCgQyVr@14zdqzh44X4SI1kkJxODzBLl92icKyfHk2iAgFJgPsN8lRKBTI48GC2TD5KywYVduPbdnH9hLPfIQZORdBqPiboKaOvWxOUvN@k0KEQvS/xmPk9Di5Pq4CXwXXDoASoN91/QM

@Shaggy WOW man that's sick! How could I not see .pop() ... I was looking for a parseInt replacement, but didn't come up with ("0x"+c) ... I thought I had tried the (W=d[s])[0] pattern and it failed, must've made some typo then ... I'll incorporate all of these tricks tomorrow. This is huge, thank you!

@PaulThomann, sometimes, even for the most experienced golfers, things can get a bit "wood for the trees" - you can get so caught up in optimising your method that you can miss some obvious golfs in your code, or you get so caught up in golfing your code that you completely overlook the fact that there might be a better method. Pretty sure that, with a rewrite, you could get rid of the fors and return, make this a one-liner and get much closer to, or even under, 200 bytes.

JavaScript (Firefox), 1050 bytes
c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r)
_='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop())

f =

c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r)
_='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop())

console.log(f(0xFF04FE));
console.log(f(0xFFFFFF));
console.log(f(0x457CCB));
document.body.style.color = 'black';

Third JavaScript language in this question now...
getComputedStyle always returns colors in rgb(x, y, z) form if alpha == 1 on Firefox.
_ variable holds the string with all color names in the form BlackNavyDarkblueMediumblueBlueDarkgreen...White.
Save 11 bytes thanks to Kevin Cruijssen by removing unnecessary colors.
Save ~350 bytes thanks to Arnauld by introducing some strange packing algorithm.

You should save 350+ bytes by RegPack'ing your string, or maybe the entire code, this time. ;)

Save a few bytes by assigning document.body to b within getComputedStyle, allowing you to remove the enclosing parentheses.

FuchsiaMagenta and AquaCyan can both be either of the two instead of both, since they're (just like the Gray/Grey) the same color-codes.

@Shaggy but the parentheses are still required by ,r maybe

@tsh, use &&r instead.

A nifty potential improvement would be to find the color names by brute force; recursively build all alphabetical strings of up to 20 characters, try assigning them to style.color, then see if getComputedStyle indicates that the color has changed. That way, no need to bake the list (compressed or not) into the code. However, even doing that brute force up to 6 characters starts to be slow, so to finish before the universe ends you'd some clever optimisations. Even so, I reckon the byte count here could be halved while still keeping the resulting function runnable over a weekend.

05AB1E, 1175 bytes
.•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕ×¤JÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWÅ¬Žø%ð°¤]γθγçkÌã©Ð:8•
#`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—Ä¯0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇâ‡Ž0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿÇ¨0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇÝ›È‡Ž0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛØ‰„¸“„0 K#•zÑÄªåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ć†¥2Œ’Ktθu1SнdwÎ€(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“Ã §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºöì¾«Â
åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••Oи¤•в.¥εI‚₄S₁β+₁в€¦`αO}Wkè

That took quite a while.. 139 colors to create a string of.. >.>
Takes input as a 24-bit integers to save 1 byte.
Try it online or verify a few more test cases. (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.)
Explanation:
First we generate all the color-strings:
.•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕ×¤JÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWÅ¬Žø%ð°¤]γθγçkÌã©Ð:8•
                '# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue"
  #              # Split this string on spaces
   `             # Push each string separately to the stack
    “ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—Ä¯0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇâ‡Ž0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿÇ¨0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇÝ›È‡Ž0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛØ‰„¸“
                 # Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white"
                 # Where all `ÿ` are automatically filled with the strings on the stack
      „0 K       # Remove all "0 " from this string
          #      # Split the colors on spaces

Then we generate a list of forward differences (deltas) between each integer value of the colors:
•zÑÄªåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ć†¥2Œ’Ktθu1SнdwÎ€(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“Ã §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºöì¾«Â
åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;•
                 # Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791
•Oи¤•            # Push compressed integer 1579378
     в           # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15]
      .¥         # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215]

Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin .x..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier:
ε                # Map each integer to:
 I‚              #  Pair it with the input-integer
   ₄S            #  Push 1000, split to digits: [1,0,0,0]
     ₁β          #  Converted from base-256 to an integer: 16777216
       +         #  Add that to both integers in the pair
        ₁в       #  Convert both integers to base-256 as list (we now have [1,R,G,B])
          €¦     #  Remove the leading 1
            `    #  Push both lists to the stack
             α   #  Get the absolute difference between the lists (at the same indices)
              O  #  Sum these differences
}W               # After the map: get the minimum (without popping the list itself)
  k              # Get the index of this minimum in the list
   è             # And use it to index into the string-color list
                 # (after which the result is output implicitly)

See this 05AB1E tip of mine (all four sections) to understand why:

.•ŒRǝ...Ð:8• is "chiffon lavenderblush papayawhip ... cyan turquoise steelblue"
“ƒÏª©–°0‡—...‡Ž0ŠÛØ‰„¸“ is "black navy dark0 blue ... light0 yellow ivory white"
•zÑÄ...C±;• is 199...791
•Oи¤• is 1579378
•zÑÄ...C±;••Oи¤•в is [128,11,66,...,224,16,15]

That. Is the longest 05AB1E program. I have ever seen.

@connectyourcharger Yep, by far the largest I've written, beating my previous largest program of 176 bytes.. xD Not really something to be proud of with a code-golfing challenge, though. ;)

You earned my upvote though :)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Add 2 positive integers by playing with bits
Given 2 positive integers in any format you'd like, return their sum using only logic gates and bit shifts (see example below). Don't worry about overflow.
EDIT: Using pre-written addition is obviously not allowed. So no a + b, Add(a, b), a - (-b) etc.
This is code golf, so standard loopholes apply. Shortest program in characters wins.
Some test cases:
3, 4 => 7
5, 7 => 12
9, 10 => 19
12, 31 => 43

Example code in C#, readable (471 characters):
int Add(int numA, int numB)
{
    int result = 0;
    int mask = 1;
    int carryOver = 0;
    while (numA > 0 || numB > 0)
    {
        int A_bit = numA & 1;
        int B_bit = numB & 1;
        if ((carryOver ^ A_bit ^ B_bit) == 1)
        {
            result |= mask;
        }
        carryOver = carryOver == 1 ? A_bit | B_bit : A_bit & B_bit;
        numA >>= 1;
        numB >>= 1;
        mask <<= 1;
    }
    return carryOver == 1 ? result | mask : result;
}

Example code in C#, unreadable (118 characters):
int r=0,m=1,c=0;while(a>0|b>0){int A=a&1,B=b&1;if((c^A^B)==1)r|=m;c=c==1?A|B:A&B;a>>=1;b>>=1;m<<=1;}return c==1?r|m:r;

I see what you're trying to do with this challenge, but it's basically hopeless to get answers that "play with bits" by banning arithmetic operators. There's too many ways to "cheat" with built-ins like sum and string concatenation, and trying to ban these leads to ambiguity and disagreements about the spirit of the challenge. After many attempts at such challenges, the community has come to the conclusion that Do X without Y challenges are a bad idea.

@xnor Using any other function to calculate it for you is obviously not allowed.

See Patching out approaches and Non-observable requirements and other "Things to avoid".

If we must use bit-bashing, then it should be more firmly stated, and not rely on the spurious leap that not using arithmetic operators would implicitly force us to "play with the bits."

I've edited the question to explicitly state that you must use only logic gates and shifts.

@Bip Is my answer acceptable?

@Adám Yes, I don't know the language but according to your explanation you only played with bits.

@Bip Shouldn't you give others a chance before you accept an answer? Maybe someone who could beat my code length wasn't here during this past hour…

@Bip Since it looks like you want to only allow functions on a whitelist, take a look at the [tag:atomic-code-golf] tag. I think the best way to handle these is to describe a mini-language describing exactly what's allowed and how many points or characters each operation costs.

using only logic gates and bit shifts But your example also uses logical branching (if, ?), loops (while), arithmetical comparisons (>)... I'm afrait it is going to be hard to define the allowed operations throughly and without making assumptions about language features

Hello welcome to the site.  This challenge could potentially be worked into something that meets our standards.  For that I would recommend putting it in the sandbox on the meta so that more experienced users can point out issues they see.

I've VTCed as unclear as your spec requires binary input but your test cases contradict that.

JavaScript (ES6), 71 bytes
Takes input as (a)(b).
a=>g=(b,r=0,m=1,c,y=a&m,z=b&m)=>m?g(b,!(y^z)^!c?r|m:r,m<<1,c?y|z:y&z):r

Try it online!

Looks like the spec (unnecessarily) requires input in binary.

@Shaggy Neither the test cases nor the example code seem to do that, though.

I think you overcomplicated it.

@DaniilTutubalin Definitely. It's just a port of the example code.

JavaScript (ES6), 28 bytes
f=(a,b)=>b?f(a^b,(a&b)<<1):a

Try it online!

Logicode, 185 Bytes
Seeing as Logicode only has AND, OR, and NOT operators, I thought it might be fun to try to implement addition in Logicode for this challenge.
circ t(a,m)->cond a&m->1/0
circ x(a,b)->(a&!b)|(b&!a)
circ f(a,b,c,m,n)->cond n&10000000->0/f(a,b,(t(a,m)&(t(b,m)|c))|(t(b,m)&c),m+0,n+0)+x(x(t(a,m),t(b,m)),c)
circ a(a,b)->f(a,b,0,1,1)

Try it Online!

C (gcc)
Not golfed to the max
c;d(a,b){while(b){
c=1;while(~b&c)b^=c,c<<=1;b^=c;
c=1;while( a&c)a^=c,c<<=1;a^=c;}
return a;}

Explanation, it's basically
while(b--)a++;

Will not work for negative b
Try it online

85 bytes

APL (Dyalog Unicode), 13 bytesSBCS
Anonymous tacit prefix function. Takes list of two equal-length binary representations.
⊃(≠/,1⌽¨∧/)⍣≡

Try it online!
(…)⍣≡ apply the following function until two consecutive applications are identical:
 ∧/ AND of the two (lit. AND-reduce, so this enclose the result to reduce rank)
 1⌽¨ shift the content of that enclosure a single step left
 ≠/, prepend the XOR of the two (lit. XOR-reduction, so this also encloses)
eventually the all carries have been done, so the second element (AND) is all-zero
⊃ pick the first element

Hey, I've downvoted this answer since I don't think one ought to leave answers if they are unclear on the challenge requirements.  I usually give people the benefit of the doubt when I am unclear on a challenge, but your comment asking if your answer is valid seems to indicate that you to are not entirely clear on what is allowed.

@SriotchilismO'Zaic I had no doubt at the time of posting, since OP said without using the +, -, /, * operators of your language. However, after I posted, OP was edited to say only logic gates and bit shifts, leaving me in doubt, since I also use fix-point, concatenation, and selection.

Retina 0.8.2, 65 bytes
+`(.?)(,\d*)(\d)
$2;$1$3
+`(.),
,;$1
{`00
0
01|10
1
}`;11
1;0
\D

Try it online! Link includes test cases in decimal; the header and footer perform base 2 conversion. Explanation:
+`(.?)(,\d*)(\d)
$2;$1$3
+`(.),
,;$1

Interleave the bits of both numbers, starting from the right.
{`00
0
01|10
1
}`;11
1;0

XOR each pair of bits together, and also AND the bits and carry 1 in that case. Repeat so that the carries propagate if necessary.
\D

Delete the separator punctuation.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Do the 26 richest billionaires own as much wealth as the poorest 3.8 billion people?
Introduction:
A few days ago I read this post with the same title when I came across it in the HNQ. It asks if this claim of US presidential candidate Bernie Sanders is true or not:

Today the world's richest 26 billionaires, 26, now own as much wealth as the poorest 3.8 billion people on the planet, half of the world's population.
Link to video

Please go to the question itself for answers and discussions there.
As for the actual challenge based on this claim:
Challenge:
Two inputs: a descending sorted number-list \$L\$ and a number \$n\$ (where \$n\$ is \$1\leq n\lt \text{length of }L\$).
Output: the longest possible suffix sub-list of \$L\$ for which the total sum is \$\leq\$ the sum of the first \$n\$ values in list \$L\$.
Example:
Inputs: \$L\$ = [500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3] and \$n=2\$.
Output: [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]
Why?
The first \$n=2\$ values of the list \$L\$ ([500,200]) sum to 700. If we take all suffixes of the remaining numbers, as well as their sums:
Suffix:                                                                  Sum:

[-3]                                                                     -3
[-2,-3]                                                                  -5
[0,-2,-3]                                                                -5
[1,0,-2,-3]                                                              -4
[2,1,0,-2,-3]                                                            -2
[2,2,1,0,-2,-3]                                                          0
[3,2,2,1,0,-2,-3]                                                        3
[5,3,2,2,1,0,-2,-3]                                                      8
[5,5,3,2,2,1,0,-2,-3]                                                    13
[5,5,5,3,2,2,1,0,-2,-3]                                                  18
[5,5,5,5,3,2,2,1,0,-2,-3]                                                23
[10,5,5,5,5,3,2,2,1,0,-2,-3]                                             33
[10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                          43
[20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                       63
[30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                    93
[30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                 123
[40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                              163
[50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                           213
[55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                        268
[75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                     343
[75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                  418
[100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]              518
[125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]          643
[150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]      793
[150,150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]  943

The longest suffix which has a sum lower than or equal to 700 is [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3] with a sum of 643, so that is our result.
Challenge rules:

Values in the first \$n\$ prefix aren't counted towards the output-suffix. I.e. inputs \$L\$ = [10,5,5,3] and \$n=2\$ would result in [5,3], and not [5,5,3].
I/O is flexible. You can input \$L\$ as a list/stream/array of integers/decimals/strings, a single delimited string, one by one through STDIN, etc. You can output as a list/stream/array of integers/decimals/strings as well, print/return a delimited string, print a number on each newline, etc. Your call.
The output is guarantees to be non-empty. So you won't have to deal with test cases like \$L\$ = [-5,-10,-13] and \$n=2\$ resulting in [].
Both (or either) the input and/or output may also be in ascending order instead of descending order if you choose to.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:
Inputs: L=[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3], n=2
Output: [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]

Inputs: L=[10,5,5,3], n=2
Output: [5,3]

Inputs: L=[7,2,1,-2,-4,-5,-10,-12], n=7
Output: [-12]

Inputs: L=[30,20,10,0,-10,-20,-30], n=1
Output: [20,10,0,-10,-20,-30]

Inputs: L=[100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5], n=1
Output: [15,5,5,5,5,5,5,5,5,5,5,5,5,5]

Inputs: L=[0,-5,-10,-15], n=2
Output: [-10,-15]

Inputs: L=[1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250], n=2
Output: [525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250]

Inputs: L=[10,5,5], n=1
Output: [5,5]

Can I write an answer that only works with positive (or maybe nonnegative; I haven't written it yet) integers due to the lack of an integer type in the language?

@Neil I assume you're talking about Retina here? But sure, you can assume all the values are non-negative in that case. Although, do you best to also have a second version that works for negative values, because I have the feeling that might actually be achievable (with a huge increase in byte-count and some work-arounds); which is more of a general feeling than actual fact, not sure if it is indeed possible to work-around the negative values part).

The real test case would look like that: [131000000000, 96500000000, 82500000000, 76000000000, (7.7 billion more entries)] :p

What about the scenario where none of the values meet the criteria: [1,2,3] n = 1? What do you want for output?

@ouflak See the third challenge rule: "The output is guarantees to be non-empty. So you won't have to deal with test cases like L = [-5,-10,-13] and n=2 resulting in []." Also, the input-list is guaranteed to be sorted descending (or ascending if you choose to), so [1,2,3] isn't a valid input-list to begin with (unless you choose ascending input, in which case [1,2] would be the result).

@KevinCruijssen, Got it. The top three contenders are returning [] safely anyway.

From review queue: This question is not primarily opinion-based. The background of the challenge is based on a claim, and the challenge does not attempt to assert its truthiness. The challenge itself has an objective winning criterion and is therefore on-topic.

@mbomb007 Lol, did someone vote this challenge as primarily opinion based? That's a first for one of my challenges. ;D

Yeah. They probably didn't read the first part of your challenge very closely.

Well, I got a Retina answer for non-negative input, but I'm not going to be able to get it to work for the case where the sum of the first n elements of L is negative...

Nibbles, 10 bytes (20 nibbles)
/|.`,,$>$>_@++<_@-~+

  .                     # map over
   `,                   # range from zero up to
     ,$                 # length of arg1 minus 1
       >$               #   drop that many elements from
           @            #   arg1
         >_             #   with arg2 elements already dropped
 |                      # now filter only those lists whose
                   +    #   sum
                 -~     #   subtracted from one
            +           #   added to
             +          #   the sum of
              <_        #   the first arg2 elements
                @       #   of arg1
                        #   is truthy = greater than zero
/                       # fold over this list of lists from right
                        #   returning the left arg each time
                        #   (so, output the first filtered list)

You should ask if Nibbles can be added to ATO. :) (If ATO is still being updated, which I think it is - unlike TIO.)

@KevinCruijssen Good idea. Requested.

C# (Visual C# Interactive Compiler), 88 81 69 68 63 bytes
-4 bytes thanks to LiefdeWen

a=>b=>a.Skip(b).Where((x,i)=>a.Skip(i+b).Sum()<a.Take(b).Sum())

Try it online!

I'm thinking you could shave off two more by eliminating +b in the Skip call; it's redundant to check the first n list, but I think it's still correct.

@TheRubberDuck nope, had to add it in for the case where the prefix and suffix overlap. I.e [10,5,5,3], n = 2

64 bytes

@LiefdeWen nice! it's actually less too if we use a curried function

@ExpiredData Oh yeah, forgot I removed it.

EXAPUNKS (2 EXAs, 30 Instructions, 594-byte solution file)
I've wanted to try a code golf challenge in EXAPUNKS for a while, and you looked like the best fit I could find, so, congrats!
Input via files 200 and 201, for L and n respectively. Output via a new file. L and the output are in ascending order.
Basically, XA sums the last n values in L, then sends it to XB. It then seeks to the beginning of L and sends each value one-by-one to XB. XB first receives the total from XA and stores it in register X. It then receives values one-by-one from XA, deducting the new value from X, and writing those values to the output file until X < 0.
XA
GRAB 201
SUBI T F T
DROP
GRAB 200
SEEK 9999
SEEK T
MARK FIRST_SUM
ADDI F X X
ADDI T 1 T
SEEK -1
VOID F
TJMP FIRST_SUM
COPY X M
SEEK -9999
MARK SECOND_SUM
COPY F M
TEST EOF
FJMP SECOND_SUM
KILL

XB
MAKE
COPY M X
MARK LOOP
COPY M T
COPY T F
SUBI X T X
TEST X > 0
TJMP LOOP
SEEK -1
VOID F
KILL

JavaScript for the level here

IIRC doesn't exapunks have a way to save solutions?  If so you should use byte count rather than in game instructions.

@SriotchilismO'Zaic, yep, I didn't think the files were supposed to be easily-accessible, but I've just found them. I'll add the size-on-disk. A bunch of metadata that I didn't write gets stored alongside it, but I guess this is the best way to actually get a single "byte count" out of this game.

I'd love to take the time to look at these files and see if there is a way to sort of golf the metadata down.  I also wonder if some instructions take more memory than others.

@SriotchilismO'Zaic, they actually do. All the instructions get stored as plaintext, so for a start we can turn all the marks to single-letter identifiers. The name of your solution is in there, so we can remove a few bytes by calling the solution 'a'. Some parts of it also seem related to the virtual network you created for the EXA, though. Honestly, I think the "fairest" way to score EXAPUNKS solutions is to either use the byte count of the actual code, or the number of instructions. This might be worth a meta post...

Ah, never mind, this is already covered by https://codegolf.meta.stackexchange.com/questions/13107/what-is-a-character-encoding-exactly/13111#13111; "there must be an actual file with the claimed byte count that, when fed to your interpreter, runs the intended program".

@ymbirtt I suppose the question then comes down to could you write an interpreter which will look at the instructions and convert into the saved data? Well trivially yes, just write a program which inputs for you from the source.. it would count as a different language though.

Since the official metric is bytes, you should rename both EXAs to the empty string, and rename all marks to a single letter each.

Also it doesn't look like those KILL commands do anything useful.

@Grimy, you're right that the EXAs and marks should be renamed, but the KILL commands are actually necessary to cause the program to terminate. If XB were to simply terminate with the correct file, then XA will deadlock on COPY F M. If XA were to simply terminate having sent the entire file, then XB will deadlock on COPY M T

Python 2, 60 bytes
l,n=input()
s=sum(l[:n])
while sum(l[n:])>s:n+=1
print l[n:]

Try it online!

Explanation:
First takes the sum of the first n items.
Then the sum of each sublist is compared to this sum. As soon as one is not larger, we stop.
Then the resulting (longest) sublist is printed.

actually the most readable one +1

05AB1E, 14 12 bytes
Saved 2 bytes thanks to Grimy
.$ΔDOI¹£O›.$

Try it online!
Explanation
.$               # drop the first n entries of the list
  Δ              # repeat the following code until the result doesn't change
   DO            # duplicate and sum the copy
     I¹£O        # calculate the sum of the first n items of the input
         ›.$     # if the current sum is greater than the sum of the first n items
                 # remove the first item of the current list

'Exactly' the same as what I had prepared as solution. And by 'exactly' I mean mine was .$.sʒO²¹£O>‹}θ. :)

@KevinCruijssen: Hopefully it's optimal then :)

@KevinCruijssen here's 12

@Grimy: Wow, that's a really cool use of .$ with Δ

That .$ inside the Δ could simply be i¦, I only used .$ to look cool (and in the hope that it could be merged with the other .$, which didn't pan out).

ASCII-only 12 (using a different input method).

@Grimy: Huh. I never knew | overwrote the last-input, interesting.

@Grimy: See this vs this. Normally when all inputs are consumed, the last input is implicitly used for all instances of next input. Using | here makes the result of | become the last input instead of what was actually the last input.

J, 18 bytes
}.#~+/@{.>:+/\.@}.

Try it online!
Explanation:
A dyadic verb, taking n as its left argument and L - as its right argument.
                }.  drop the first n items from L
               @    and
             \.     for each suffix (starting from the longest)
           +/       find its sum
         >.         is this sum smaller or equal than (results in a boolean vector)
    +/              the sum
      @             of
       {.           the first n items of L
  #~                use the 1s in the boolean vector to copy the respective
}.                  elements of L (without the first n)

Ruby, 47 43 bytes
Takes an ascending list as input. Removes \$n\$ items from the end of the array to get the initial sum, then continue removing items until the remaining elements' sum is less than the initial sum.
-4 bytes by reading the spec more closely.
->a,n{s=a.pop(n).sum;a.pop while a.sum>s;a}

Try it online!

R, 53 55 bytes
@Giuseppe saved me 2 bytes changing the way remove was done

function(n,L,Y=rev(L[0:-n]))Y[cumsum(Y)<=sum(L[1:n])]

Try it online!
Takes the input as descending and outputs in ascending as allowed by rule 4.

Y is the rev of L with 1:n removed using 0:-n
returns from Y where cumulative sum is less then equal to the sum of L[X]

@Giuseppe as always thanks.  Tried removing the X using -(1:n) but of course that was the same size, so left it

JavaScript (ES6), 66 bytes
Takes input as (a)(n) with the list in ascending order.
a=>n=>(g=s=>n?g(s+a.pop(n--)):eval(a.join`+`)>s?g(s,a.pop()):a)(0)

Try it online!
Commented
a => n =>               // a[] = list, n = number of richest guys
  ( g = s =>            // g is a recursive function taking a sum s
    n ?                 // if n is not equal to 0:
      g(s + a.pop(n--)) //   recursive call: add the last entry to s and decrement n
    :                   // else:
      eval(a.join`+`)   //   if the sum of the remaining entries
      > s ?             //   is greater than s:
        g(s, a.pop())   //     recursive call with the last entry removed
      :                 //   else:
        a               //     stop recursion and return a[]
  )(0)                  // initial call to g with s = 0

@KevinCruijssen Seems like I misread the requirement. Should be fixed now.

And unlike some other answers that had fixed the same issue, without an increase in byte-count. :) (And partially my bad, should have included a test case for $\leq$ to begin with..)

Python 2, 59 bytes
Also compatible with Python 3
f=lambda l,n:l[n:]*(sum(l)/2>=l.pop(n)+sum(l[n:]))or f(l,n)

Try it online!

Explanation
The sum of the suffix is compared to half of the sum of the whole list. If the sum of the suffix is smaller or equal, the suffix is returned. If not, the function is called recursively with the first item of the suffix popped out.

Pyth, 16 15 bytes
efgs>vzQsT._<vz

Try it online!
The input list is expected to be sorted in ascending order, rather than descending as is used in the examples.
It's at times like this when I really wish Pyth had a single token operator to access the second input more than once (E evaluates the next line of input, but repeated calls discard the previous value read).
efgs>vzQsT._<vzQ   Implicit: Q=eval(input()), z=input() - that is, Q is list, z is string n
                   Trailing Q inferred
             vz    Evaluate z as integer
            <  Q   Remove the above number of elements from the end of Q
          ._       Generate a list of all prefixes of the above
 f                 Filter keep elements of the above, as T, where:
    >vzQ             Take the last z elements of Q
   s                 Sum
  g                  Is the above greater than or equal to...
        sT           ... the sum of T?
e                  Take the last remaining element, implicit print

Edit: saved 1 byte thanks to MrXcoder

Stax, 12 bytes
îo╧╫Σ↑>'qµΣº

Run and debug it at staxlang.xyz!
Nicer version
Unpacked (14 bytes) and explanation:
:/|]{|+n|+>!}j
:/                Split array at index.
  |]              Suffixes. The bit after the split (the poor) is on top for this.
    {       }j    First item in array that yields truthy under the block:
     |+             Sum array (collective wealth of the many).
       n            Copy second item to top of stack.
        |+          Sum again. Wasted computation, but this location saves a byte.
          >!        Second item on stack less than or equal to first?

By consensus, I can leave this result on the stack. Stax will attempt an implicit print, which might fail, but appending an m to the unpacked program lets you see the output nicely.
Looks like { ... }j is the same as { ... fh. Huh. Edit: That's not quite the case; the only the former will stop when it gets a truthy result, possibly avoiding side effects or a fatal error later on.

JavaScript, 64 bytes
f=(a,n,s=0,[h,...t]=a)=>n<1?f(a)>s?f(t,0,s):a:1/h?f(t,n-1,s+h):s

Try it online!
f=(
  a,               // remaining array
  n,               // if n >= 0: we try to find suffix <= s + a[0..n]
                   // if n is NaN (or undefined): we calculate sum(a) + s
  s = 0,           // previous sum
  [h, ...t] = a    // split array (a) into head (h) and tail (t)
) => (n < 1 ?      // if n == 0
  f(a) > s ?       //   if sum(a) > s
    f(t,0,s) :     //     drop head and test tail again
    a :            //   otherwise, a is the answer
  1 / h ?          // if a is not empty
    f(t,n-1,s+h) : //   add head to sum and recurse
    s              //   we only reach here if n is NaN, return the sum
)

APL (Dyalog Unicode), 23 21 bytesSBCS
Anonymous prefix lambda, taking \$n\$ as left argument and \$L\$ as right argument.
{⍵↓⍨⍺⌈⊥⍨(+/⍺↑⍵)<+\⌽⍵}

Try it online!
{…} "dfn"; \$n\$ is ⍺ (leftmost Greek letter) and \$L\$ is ⍵ (rightmost Greek letter):
 ⌽⍵ reverse \$L\$
 +\ prefix sums of that
 (…)< Boolean mask where less than:
  ⍺↑⍵ take the first \$n\$ elements of \$L\$
  +/ sum those
 ⊥⍨ count trailing truths
 ⍺⌈ the maximum of \$n\$ and that
 ⍵↓⍨ drop that many elements from the front of \$L\$

@KevinCruijssen Nicely spotted. Fixed.

MATL, 13 12 bytes
1 byte saved thanks to @Giuseppe, based on the answer by @MickyT.
:&)PtYsbs>~)

Output is in ascending order.
Try it online! Or verify all test cases.
Explanation
Consider inputs 2 and [500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3].
:      % Implicit input: n. Push [1 2 ... n]
       % STACK: [1 2]
&)     % Implicit input: array. Two-output indexing: pushes the subarray
       % indexed by [1 2 ... n] and the remaining subarray
       % STACK: [500 200], [150 150 125 ... -2 -3]
P      % Flip
       % STACK: [500 200], [-3 -2 ... 125 150 150]
t      % Duplicate top of the stack
       % STACK: [500 200], [-3 -2 ... 125 150 150], [-3 -2 ... 125 150 150]
Ys     % Cumulative sum
       % STACK: [500 200], [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946]
b      % Bubble up in the stack
       % STACK: [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946], [500 200]
s      % Sum
       % STACK: [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946], 7
>~     % Greater than, negate; element-wise
       % STACK: [-3 -2 ... 125 150 150], [1 1 ... 1 0 0]
)      % Index. Implicit display
       % STACK: [-3 -2 ... 125]

Jelly, 13 12 bytes
ṫḊÐƤS>¥ÞḣS¥Ḣ

Try it online!
Thanks to @JonathanAllan for saving a byte!
A dyadic link taking the list of values \$L\$ as left argument and the number \$n\$ as right.
Explanation
ṫ            | Tail: take all values of L from the nth onwards (which is actually one too many; dealt with below)
 ḊÐƤ         | Take all suffixes, removing the first value from each. This will yield a list of all possible suffixes of L that exclude the first n values
       Þ     | Sort by:
    S>¥ ḣS¥  | - The sum is greater than the sum of the first n values of L
           Ḣ | Take the first resulting list and return from link (implicitly output when called as a full program)

You can save a byte by sorting instead of filtering: ṫḊÐƤS>¥ÞḣS¥Ḣ

PowerShell, 99 97 bytes
param($n,$l)do{$a+=$l[$i++]}until($a-gt($l[-1..-$n]-join'+'|iex)-or$i-gt$l.count-$n)$l[($i-2)..0]

Try it online!
Takes list in ascending order, output is descending (because it was easier to compare to the test cases :^))
Goes through the list backwards forwards, comparing the accumulator to the last n entries added together (via gluing them together with +s and passing the resulting string to invoke-expression). The Until loop needed additional logic to handle going into the Rich Neighborhood because it wouldn't stop if we're still not richer than the Rich Guys until we churn through the entire list.
Unrolled:
param($n,$list)
do{
  $acc+=$list[$i++]
}until($acc -gt ($list[-1..-$n] -join '+'|invoke-expression) -or ($i -eq $list.count-$n))
$list[($i-2)..0]

APL+WIN, 27 bytes
Prompts for input of L then n.
⌽((+/n↑v)≥+\m)/m←⌽(n←⎕)↓v←⎕

Try it online! Courtesy of Dyalog Classic

Japt, 16 bytes
£sV+YÃæ_x §U¯V x

Try it
£sV+YÃæ_x §U¯V x     :Implicit input of U=L and V=n
£                    :Map U, with Y being the 0-based indices
 sV+Y                :  Slice U from index V+Y
     Ã               :End map
      æ              :First element that returns true
       _             :When passed through the following function
        x            :  Reduce by addition
          §          :  Less than or equal to
           U¯V       :    Slice U to index V
               x     :    Reduce by addition

Gaia, 12 bytes
eSe¤Σ¤┅⟪Σ⊃⟫∇

Try it online!
I think there's a byte I can golf if I get the stack just right.
e	| eval first input as Gaia code
S	| Split into a list of ["first n elements" "rest of elements"]
e	| dump onto stack
¤Σ	| swap and take the sum (sum of first n elements)
¤┅	| swap and take suffixes
⟪  ⟫∇	| return the first element of suffixes where:
 Σ⊃	| the sum(first n elements) ≥ sum(suffix)

Haskell, 46 bytes
Displeased with how this looks; hope I’m just missing some obvious golfs.
n#l=until(((sum$take n l)>=).sum)tail$drop n l

Try it online!
I tried getting the prefix and suffix using splitAt and pattern matching in a guard, but that turned out to be 3 bytes more.
Planning on trying to convert to a recursive function with guards later to see if that lowers the byte count.
Explanation
n # l = until (((sum $ take n l) >= ) . sum) tail $ drop n l
n # l =                                                        -- define infix operator
n                                                              --  the number of elements
    l                                                          --  the list
        until                                                  -- until
                                        sum                    --  the sum of the suffix
               ((sum $ take n l) >=)                           --  is <= the sum of the prefix
                                             tail              --  remove the first element
                                                    drop n l   -- the suffix

What I refer to as "the prefix" is the first n elements and "the suffix" is the rest of the list.

Retina 0.8.2, 99 bytes
\d+
$*
^
;,
+`;,(1+)(,.*)1$
$1;$2
,
;$'¶$`,
;.*(;.*)
$1$1
T`,`_`.*;
1G`(1+);\1;
.*;

(1*),
$.1,
,$

Try it online! Link only includes some test cases; I could get it to work in some cases with negative numbers at a cost of 12 bytes (in particular the first n entries in L still need to be positive; theoretically I could probably only require the sum of the first n entries to be positive). Explanation:
\d+
$*

Convert to unary.
^
;,

Insert a marker at the start of L.
+`;,(1+)(,.*)1$
$1;$2

Move it down the list n times, summing as we go. This deletes n but its comma remains.
,
;$'¶$`,

Create an entry for each suffix of L.
;.*(;.*)
$1$1

Replace the middle with a copy of the suffix.
T`,`_`.*;

Sum the copy of the suffix.
1G`(1+);\1;

Take the first entry where the suffix sum does not exceed the prefix sum.
.*;

Delete the sums.
(1*),
$.1,

Convert to decimal.
.,$

Delete the trailing comma that came before n.

Nice answer. :) Could you perhaps add a TIO link to the version that's 12 bytes longer containing negative numbers. And np that it doesn't work when the first $n$ numbers sum to a negative value. As long as it works with positive integers it's still fine. Well done.

@KevinCruijssen My negative number version turned out to be prohibitively slow, but I managed to fix that by using the r option, so I've now linked it in with some test cases.

Charcoal, 17 bytes
ＩΦθ¬∨‹κη‹Σ…θηΣ✂θκ

Try it online! Link is to verbose version of code. Explanation:
  θ                 Input `L`
 Φ ¬                Filter out elements where
      κ             Current index
     ‹              Is less than
       η            Input `n`
    ∨               Logical Or
           θ        Input `L`
          … η       First `n` terms
         Σ          Summed
        ‹           Is less than
              ✂θκ   Remainder of `L`
             Σ      Summed
Ｉ                   Cast to string
                    Implicitly print on separate lines

Red, 63 bytes
func[L n][s: sum take/part L n forall L[if s >= sum L[break]]L]

Try it online!

PowerShell, 86 bytes
param($n,$l)$l|?{$k++-ge$n}|?{(&{$l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]};$s})-ge0}

Try it online!
Unrolled:
param($n,$list)
$list|?{$k++-ge$n}|?{                               # tail elements after $n only
    $sumLeftSegmentMinusSumRightSgement = &{        # calc in a new scope to reinit variables $s, $i
        $l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]} # sum(list[0..n-1]) - sum(list[k-1..list.Count-1])
        $s                                          # output sum to the outer scope
    }
    $sumLeftSegmentMinusSumRightSgement -ge 0       # output elements where sum >= 0
}

MathGolf, 13 bytes
(‼≥≤Σ\æ╞`Σ≥▼Þ

Try it online!
Explanation
Takes input as n L
(               pops n and decrements (TOS is n-1)
 ‼              apply next two operators to stack simultaneously
  ≥             slice L[n-1:] (gets all elements with index >= n-1)
   ≤            slice L[:n] (gets all elements with index <= n-1)
    Σ           get sum of topmost list (this is the sum of n largest elements)
     \          swap top elements
      æ    ▼    do while false with pop using block of length 4
       ╞        discard from left of string/array
        `       duplicate the top two items on the stack
         Σ      sum the list which is on top
          ≥     is the sum of the partial list >= the desired sum?
            Þ   discard everything but TOS

The reason why this works is that in the first step, we actually divide the list into two overlapping parts. As an example, L = [4, 3, 2, 1], n = 2 will split up the list as [3, 2, 1] and [4, 3]. The reason for having an extra element in the first list is that in the loop, the first thing that happens is a discard. If an extra element was not prepended, the cases where the output should be the entire rest of the list would fail.

Wolfram Language (Mathematica), 40 bytes
Drop@##//.{a_,b__}/;a+b>Tr@Take@##:>{b}&

Try it online!
Drop@##                     (*don't include the first n values*)
 //.{a_,b__}/;a+b>Tr@Take@##(*while the remaining values sum to greater than the sum of the first n*)
     :>{b}&                 (*drop the first element*)

Vyxal, 11 bytes
Ẏ∑£ȯÞK≬∑¥≤∵

Try it Online! Fixed thanks to one of the Sʨɠɠans.
 ∑          # Sum
Ẏ           # Of first n
  £         # Stored to register
   ȯÞK      # Suffixes of rest
          ∵ # Maxmimum by...
      ≬---  # Next 3 as lambda...
       ∑    # Sum
         ≤  # Is less than (or equal to)
        ¥   # Register?

Clojure, 66 75 bytes
#(loop[v(drop %2 %)](if(>(apply + v)(apply +(take %2 %)))(recur(rest v))v))

Sadly there doesn't seem to be a shorter idiom for the total sum of a sequence.
Edit: Oh when adding examples to the Try it online! link I noticed that the original answer gave wrong results when many negative numbers were present.
The doseq uses "keys" destructuring so it should be somewhat clear which data ends up in which symbol. #(...) is an anonymous function, here I'm binding it to the symbol f:
(def f #(loop[v(drop %2 %)](if(>(apply + v)(apply +(take %2 %)))(recur(rest v))v)))

(doseq [{:keys [L n]} [{:L [10,5,5,3] :n 2}
                       {:L [7,2,1,-2,-4,-5,-10,-12] :n 7}
                       {:L [30,20,10,0,-10,-20,-30] :n 1}]]
  (println (f L n)))

Output:
(5 3)
(-12)
(20 10 0 -10 -20 -30)

Would you mind adding a TIO with test code (I see Clojure in the list)? If it isn't possible somehow (version mismatch, or using builtins that aren't available on TIO), could you include a screenshot with some of the test cases as verification that it works?

Python 3, 71 69 bytes
lambda L,n:[L[i]for i in range(len(L)-n)if sum(L[:i+1])<=sum(L[-n:])]

Try it online!

APL(NARS), 32 chars, 64 bytes
{v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵}

test and comments:
  q←{v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵}
  2 q 500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,¯2,¯3
125 100 75 75 55 50 40 30 30 20 10 10 8 5 5 5 3 2 2 1 0 ¯2 ¯3
  2 q 10,5,5,3
5 3
  ⎕fmt  7 q 7,2,1,¯2,¯4,¯5,¯10,¯12
┌1───┐
│ ¯12│
└~───┘
  2 q 0,¯5,¯10,¯15
¯10 ¯15
  ⎕fmt 1 q 100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5
┌14───────────────────────────┐
│ 15 5 5 5 5 5 5 5 5 5 5 5 5 5│
└~────────────────────────────┘
  2 q 1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,¯15,¯45,¯250
525 525 400 340 120 110 80 77 33 12 0 ¯15 ¯45 ¯250
  1 q 10,5,5
5 5
  ⎕fmt  2 q ¯5,¯10,¯13
┌0─┐
│ 0│
└~─┘
  ⎕fmt  1 q 30,20,10,0,¯10,¯20,¯30
┌6───────────────────┐
│ 20 10 0 ¯10 ¯20 ¯30│
└~───────────────────┘

   {v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵}
                             v←⍺↓⍵   v is ⍵[(⍺+1)..≢⍵]
                  {⍵↓v}¨¯1+⍳≢v        build the array of array cut v of 0..((≢v)-1) elements
               +/¨                   sum each of these element of array above
      (+/⍺↑⍵)≥                       compare ≥ with the sum of ⍵[1..⍺] obtain one bolean array
                                     has the same lenght of v
   v/⍨                               return the element of v that are 1 of the boolean array above

I reported wrongly the byte length...

MS SQL Server 2017, 271 bytes
create function f(@L nvarchar(max),@ int)returns table return
select v
from(select*,sum(iif(n<=@,v,0))over()r,sum(v)over(order by v)p
from(select row_number()over(order by-v)n,v
from STRING_SPLIT(@L,',')cross apply(select
try_parse(value as int)v)t)t)t
where p<=r and @<n

I know that using a more relation-like table to store the input data can make the code more concise, but using the character data type to store the numeric list and the STRING_SPLIT function, I get shorter the Build Schema part :)More readable version:
CREATE FUNCTION f(@L NVARCHAR(MAX), @n INT)
  RETURNS TABLE AS RETURN (
    SELECT
      v
    FROM (
      SELECT
        *,
        SUM(IIF(n<=@n, v, 0)) OVER() AS r,
        SUM(v) OVER(ORDER BY v) AS p
      FROM(
        SELECT ROW_NUMBER() OVER(ORDER BY -v) AS n, v
        FROM STRING_SPLIT(@L, ',')
        CROSS APPLY(
          SELECT TRY_PARSE(value AS INT) AS v
        ) AS t
      ) AS t
    ) AS t
    WHERE p <= r AND @n < n
  );

Try it on SQL Fiddle!

Python 3.8 (pre-release), 59 bytes
Output is in ascending Order
def f(l,n):
 s=sum(l[:n])
 while(w:=l.pop())<s:yield w;s-=w

Try it online!

Husk, 11 bytes
ḟ(≤Σ↑¹³Σ)ṫ↓

Try it online!
ḟ(≤Σ↑⁰²Σ)ṫ↓⁰²   # program with implicit arguments added
          ↓     # drop arg1 elements from arg2
         ṫ      # and get all suffixes;
ḟ(      )       # now return the first that satisfies:
       Σ        #   it's sum
  ≤             #   is less than or equal to
   Σ            #   sum of
    ↑⁰          #   first arg1 elements of
      ²         #   arg2


text:
Generating all Character possibilities with two characters
Introduction
So the Challenge is to give out all combinations with two Inputs. The length of the string is also optional and you should be able to edit this.
I've selected this channel because I thought it would be very easy to do it "normally" but the challenge itself could be very interesting. I had to create that for one of our employee to make a list with product numbers.
I quickly searched the site and I didn't found any other Challenges like this.
Challenge
So the input doesn't have to be edited so you can just take the binary system [0,1]. But you have to set the length of the string or char of the output.
You can give out all the numbers in a file. You can decide the name and also the file type.
The Shortest program in characters wins.
Example Input and Output
Input:

3

Output example.txt:
000
001
010
100
101
110
111
011

Input:

2

Output example.txt:
00
01
10
11

Related and related. EDIT: actually, this might be a dupe instead (only difference is that this challenge takes [1,0] hard-coded and the other challenge takes a list as input, and the other challenge states the output should be sorted).

Any reason why 011 is output last in the first example?

The order in the output isn't important.

It was a toss-up whether to vote to close as unclear or dupe, but I think it's clear enough that you're just asking us to count from 0 to 2**n - 1.

05AB1E, 3 bytes
TIã

Try it online or verify a few more test cases.
Explanation:
T    # Push 10
 Iã  # Take the cartesian product of "10" repeated the input amount of times
     # (and output the resulting list implicitly as result)

Python 2, 46 bytes
lambda n:map(('{:0%db}'%n).format,range(1<<n))

Try it online!


text:
Is this number a palindrome?
Input
A single integer in your language's preferred format, e.g int or an array of digits are all acceptable.
Output
A truthy or falsely value, depending on whether the given number is palindromic (same forwards and backwards)
Rules

Numbers will always be positive, at least two digits long.
This is fastest-algorithm, so lowest O(n) time complexity wins.

Test cases

123454321 - true
296296 - false
296692 - true
5499456 - false
0 - false/error/any value

In your rules you state the input is less than 99999999, but the first test case is larger than this.

You state that the input is a 16-bit integer, but 4 of the 5 test cases don't fit on 16 bits.

Indeed, the upper bound, 99999999, doesn't fit in 16 bits.

Also: specifying any upper bound makes the problem trivially O(1). You should either change to fastest-code or remove the upper bound altogether.

OK, fixed all issues.

@GezaKerecsenyi No you didn't fix the issue of an upper bound making O(1) solutions trivial.

in your language's preferred format — What if my language's integer type is bounded? (E.g. 8, 16, or 32 bits.)

@Adám I assume you're referring to C & co., with long and long long being separate? Do it for the maximum your language supports. If that means hardcoding everything up to 32 bits, sure, but that will likely not be the winning entry. The same with the upper bound: it means it's possible to hardcode everything, but that doesn't mean you should. Plus it makes the challenge pretty boring.

If boring solutions are the optimal solutions then that's a reflection of the challenge, not the solutions.

@GezaKerecsenyi if the "winning" entry is the one with the lowest O(n) score, then O(1) wins, which means that the only winning entry is the boring one...

APL (Dyalog Unicode), O(1)
⊃∘'111111111110…  …10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
Anonymous tacit prefix function.
Try it online!
Simply picks the result from a pre-compiled list.

Haha, nice. Didn't think about that. Well done! :)

@LuisMendo It works for me in FFQ/W10 but it takes a very long time to render. Let's hope OP doesn't go to 64 bits…

@Adám Ah, that was the issue here as well. It took about 1 minute (Chrome, W10)

The rules of the question have changed in a way that renders this answer invalid. (By no longer specifying a size of integer)

@pppery Also, the challenge is closed.

Java, complexity: \$O(\lfloor\log_{10}(n) + 1\rfloor)\$
boolean f(int n){
  int reverse = 0;
  //int debugIterations = 0;
  for(int palindrome = n; palindrome != 0; palindrome /= 10){
    //debugIterations++;
    int lastDigit = palindrome % 10;
    reverse = reverse * 10 + lastDigit;
  }
  //System.out.println("Debug iterations: "+debugIterations);
  return n == reverse;
}

Loops once for every digit in the input-number. Pretty straight-forward implementation tbh..
Try it online.

Java, O(1)
boolean f(int n){
  if (n <= 0 || n >= 16777216) throw new Error(n+" is not a valid input!");
  int reverse = n/10000000%10*1 + n/1000000%10*10 + n/100000%10*100 + n/10000%10*1000 + n/1000%10*10000 + n/100%10*100000 + n/10%10*1000000 + n/1%10*10000000;
  int len = (int) Math.log10(n);
  reverse/= Math.pow(10, 7-len);
  return reverse == n;
}

Try it online!
Kevin Cruijssen's answer, unrolled for 24-bit numbers.

I can't post answers since this is on hold, so this is my answer: O(1)  a=input();print(1 if a[::-1]==a and len(a)>1 else 0)

The rules of the question have changed in a way that renders this answer invalid. (By no longer specifying a size of integer)

@pppery It specifies "A single integer in your language's preferred format, e.g int", and I would consider my answer accepting an int to be as valid as it gets. It doesn't seem to disallow knowing the types size either.

APL+WIN, O(1)
Thanks to Adam for suggested changes to my original code and his explanation -  see the comments section.
Prompts for input of integer.
 17=+/(⌽17↑n)=¯17↑n←⍕⎕

Try it online!

This isn't a [code-golf] challenge, it's [fastest-algorithm].

@Kevin Cruijssen OK so how do we decide which algorithm is fastest. If you compare our examples on TIO APL looks faster?

If you compare the execution-speed it would be a [fastest-code] challenge. ;) I'm not very good at comparing complexity $O$ speeds tbh. But as the challenge is currently stated, the complexity is $O(1)$ anyway regardless of the implementation. The challenge is kinda pointless imho..

@Kevin Cruijssen OK if the op is not happy with my entry I will delete it. As APL is an interpreted language I have no idea what is going on under the hood so I do not know how it is handling the problem. I think given what you have said I agree it does seem pointless.

You should be able to guarantee O(1) with 17=+/(⌽17↑n)=¯17↑n←⍕⎕ since it always has to allocate more memory (3 bytes) than initially assigned (1 or 2 bytes), always reverses a length-17 string, always compares 17 character pairs, and always sums 17 Booleans.