text:
Clearing the most significant bit from an integer
Input
The input is a single positive integer n
Output
The output isn with its most significant bit set to 0.
Test Cases
1 -> 0
2 -> 0
10 -> 2
16 -> 0
100 -> 36
267 -> 11
350 -> 94
500 -> 244

For example: 350 in binary is 101011110. Setting its most significant bit (i.e. the leftmost 1 bit) to 0 turns it into 001011110 which is equivalent to the decimal integer 94, the output. This is OEIS A053645.

Clearing the most significant bit from 10 obviously gives 0 :D

@clabacchio I.. it... er...   wha?     (nice one)

It seems to me that the zeroes are just as significant as the ones. When you say "the most significant bit" you mean "the most significant bit that is set to one".

C (gcc), 49 44 40 39 bytes
i;f(n){for(i=1;n/i;i*=2);return n^i/2;}

Try it online!

You can replace i<=n with n/i for -1 byte. This isn't my golf, someone else tried to edit it into your post but I rolled it back because edits for golfing posts are not accepted according to our community rules.

@HyperNeutrino I saw and approved the edit just now.  Wasn't aware of that rule but it's a nice golfing tip!

Ah okay. Yeah typically people are supposed to post comments for golfing tips and OP should make the edits, but if you accepted it, it's not really as much of a problem. :)

Python 2, 27 bytes
lambda n:n^2**len(bin(n))/8

Try it online!
26 bytes
Unfortunately, this does not work for 1:
lambda n:int(bin(n)[3:],2)

Try it online!

05AB1E, 5 bytes
.²óo-

Try it online!
Removing the most significant bit from an integer N is equivalent to finding the distance from N to the highest integer power of 2 lower than N.
Thus, I used the formula N - 2floor(log2N):

.² - Logarithm with base 2.
ó - Floor to an integer.
o - 2 raised to the power of the result above.
- - Difference.

b¦C also works... doesn't it? Convert to binary, MSB is always at index 1, remove MSB, convert back.

@MagicOctopusUrn No that is wrong, fails for 1!

@MagicOctopusUrn b¦C works for 1 in the new 05AB1E version. Although I like your .²óo- more tbh. :)

Jelly, 3 bytes
BḊḄ

Try it online!
Explanation
BḊḄ  Main Link
B    Convert to binary
 Ḋ   Dequeue; remove the first element
  Ḅ  Convert from binary

Aren't Ḅ and Ḋ two-byte codepoints? This would change the overall size to 5 bytes.

@BartekBanachewicz Jelly uses its own codepage, where those chars are only 1 byte.

Thanks for asking and answering this, that has bugged me for a long time!

C (gcc) -- 59 bytes
main(i){scanf("%d",&i);return i&~(1<<31-__builtin_clz(i));}

This gcc answer uses only integer bitwise and arithmetic operations.
No logarithms here! It may have issues with an input of 0, and is totally non-portable.
It's my first answer on this site, so I'd love feedback and improvements. I sure had fun with learning bitwise expressions.

Welcome to PPCG, and great first answer! We hope you'll enjoy participating in many more challenges :-)

You don't need a full program with main, a function is a valid submission. Changing this into a function and taking input as an argument to said function saves 18 bytes.

You could even write it as a macro to save two more bytes.

Java (OpenJDK 8), 23 bytes
n->n^n.highestOneBit(n)

Try it online!
Sorry, built-in :-/

Java with a build-in that some other popular languages like .NET and Python has not?! o.Ô +1 to that. Was about to post something longer without build-ins.. Yours is 15 bytes shorter. XD

@KevinCruijssen Something like n->n^1<<(int)Math.log2(n) will work and is likely shorter than 38 bytes. It was my second (yet untested) idea, if the highestOneBit one didn't work appropriately. Out of curiosity, what was your solution

Mine was n->n^1<<(int)(Math.log(n)/Math.log(2)) because Math.log2 doesn't exist in Java. ;P Only Math.log, Math.log10 and Math.loglp are available.

I was going to post the same, only minus instead of xor. Remembered the method from this

@KevinCruijssen Oops, Math.log2 doesn't exist indeed... My bad. See? One nice method (highestOneBit) exists but not another one (Math.log2). Java is weird ;-)

Husk, 3 bytes
ḋtḋ

Try it online!
Explanation:
    -- implicit input, e.g. 350
  ḋ -- convert number to list of binary digits (TNum -> [TNum]): [1,0,1,0,1,1,1,1,0]
 t  -- remove first element: [0,1,0,1,1,1,1,0]
ḋ   -- convert list of binary digits to number ([TNum] -> TNum): 94

Similarly to the Jelly solution, this seems like it's actually 5 bytes, not 3.

@BartekBanachewicz Similarly to Jelly, Husk uses its own codepage, so this is actually 3 bytes :P

@BartekBanachewicz See here for the codepage: https://github.com/barbuz/Husk/wiki/Codepage

MATL, 8 6 bytes
B0T(XB

Try it online!
Saved two bytes thanks to Cinaski. Switching to assignment indexing instead of reference indexing was 2 bytes shorter :)
Explanation:
          % Grab input implicitly: 267
B         % Convert to binary: [1 0 0 0 0 1 0 1 1]
 0T(      % Set the first value to 0: [0 0 0 0 0 1 0 1 1]
    XB    % Convert to decimal: 11

You could have used reference indexing (also for 6 bytes), if you used 4L rather than [2J]. Another fun 6 bytes: tZlcW- (only works in MATLAB, not in TIO/Octave)

R, 28 bytes
function(x)x-2^(log2(x)%/%1)

Try it online!
Easiest to calculate the most significant bit via 2 ^ floor(log2(x)) rather than carry out base conversions, which are quite verbose in R

Python 3, 30 bytes
-8 bytes thanks to caird coinheringaahing. I typed that from memory. :o
lambda n:int('0'+bin(n)[3:],2)

Try it online!

Why not lambda n:int(bin(n)[3:],2)?

Well, a) that would error on 1, b) I'm dumb enough to not think of that. But I did fix it with a minor change. Thanks!

I've edited the code so that it works, (and saves 4 bytes)

That still errors on 1.

@cairdcoinheringaahing That was my original answer, but then I realised it errored on 1. The workaround ends up longer than a simple XOR method

Python 2, 27 bytes
lambda n:n-2**len(bin(n))/8

Try it online!
Explanation
lambda n:n-2**len(bin(n))/8  # Lambda Function: takes `n` as an argument
lambda n:                    # Declaration of Lambda Function
              len(bin(n))    # Number of bits + 2
           2**               # 2 ** this ^
                         /8  # Divide by 8 because of the extra characters in the binary representation
         n-                  # Subtract this from the original

...Just when I was working the bitwise math out. :P

@totallyhuman heh sorry but beat you to it :P

2**len(bin(n))/8 can also be spelled 1<<len(bin(n))-3, and then it will work in both 2 and 3 (no bytes saved/added).

@Mego Cool, thanks for the addition!

Ohm v2, 3 bytes
b(ó

Try it online!

32-bit x86 assembler, 10 9 7 bytes
Byte code:
0F BD C8 0F B3 C8 C3
Disassembly:
bsr ecx, eax
btr eax, ecx
ret
accepts and returns the value in the eax register.
Perform a reverse scan for the first set bit, and then reset that bit.

ARM Assembly, 46 43 bytes
(You can omit destination register on add when same as source)
clz x1,x0
add x1,1
lsl x0,x1
lsr x0,x1
ret

What flavour of ARM assembly syntax is this? My GNU assembler doesn't understand shr/shl/ret and wants instead something like lsr/lsl/bx lr.

Probably mixing syntax across multiple versions (ret is from aarch64), though I thought that the assembler would pseudo op these for you.  For purposes of here, though, using the older and direct lsl/lsr is probably correct.

Funny thing, i can do it in 1 less operation, but I the byte size goes up by 2.  Ah code golf.

Excel, 36 31 bytes
-5 bytes thanks to @IanM_Matrix1
=BIN2DEC(MID(DEC2BIN(A1),2,99))

Nothing interesting.

Reduce the size to 31 bytes by replacing REPLACE with a MID: =BIN2DEC(MID(DEC2BIN(A1),2,99))

Save a byte: BASE(A1,2) instead of DEC2BIN(A1)

@Calculuswhiz, I use Office 2010, which does not support BASE.

Mathematica, 37 bytes
Rest[#~IntegerDigits~2]~FromDigits~2&

Try it online!

JavaScript, 22 20 bytes
Saved 2 bytes thanks to ovs
a=>a^1<<Math.log2(a)

Try it online!
Another approach, 32 bytes
a=>'0b'+a.toString`2`.slice`1`^0

Try it online!

why would you do .slice`1`^0 when .slice(1)^0 would work just as well, haha

@ETHproductions. This one looks better :)

J, 6 bytes
}.&.#:

Pretty simple.
Explanation
}.&.#:
    #:  convert to list of binary digits
  &.    apply right function, then left, then the inverse of right
}.      behead

I was going to post this :(

@Cyoce Me too...

APL (Dyalog), 10 bytes
Tacit prefix function.
2⊥1↓2∘⊥⍣¯1

Try it online!
2∘⊥… decode from base-2…
 …⍣¯1 negative one time (i.e. encode in base-2)
1↓ drop the first bit
2⊥ decode from base-2

Ruby, 26 bytes
-7 Bytes thanks to Ventero.
-2 Bytes thanks to historicrat.
->n{/./=~'%b'%n;$'.to_i 2}

You can save a few bytes by just skipping the first character and dropping redundant parentheses: ->n{n.to_s(2)[1..-1].to_i 2}

->n{/./=~'%b'%n;$'.to_i 2}

@Ventero -1 is not required: ->n{n.to_s(2)[1..].to_i 2}

C (gcc), 38 bytes
Built-in in gcc used.
f(c){return c^1<<31-__builtin_clz(c);}

Replacing 31- with ~ should save two bytes.

@ThePirateBay it depends on hardware whether the shift is masked. On my computer, it will output 0.

Excel, 20 bytes
=A1-2^INT(LOG(A1,2))

Welcome to the site! :)

CJam, 7 bytes
{2b()b}

Try it online!
Explanation:
{     }  Block:         267
 2b      Binary:        [1 0 0 0 0 1 0 1 1]
   (     Pop:           [0 0 0 0 1 0 1 1] 1
    )    Increment:     [0 0 0 0 1 0 1 1] 2
     b   Base convert:  11

Reuse the MSB (which is always 1) to avoid having to delete it; the equivalent without that trick would be {2b1>2b} or {2b(;2b}.

Retina, 15 13 bytes
^(^1|\1\1)*1

Try it online!
Input and output in unary (the test suite includes conversion from and to decimal for convenience).
Explanation
This is quite easy to do in unary. All we want to do is delete the largest power of 2 from the input. We can match a power of 2 with some forward references. It's actually easier to match values of the form 2n-1, so we'll do that and match one 1 separately:
^(^1|\1\1)*1

The group 1 either matches a single 1 at the beginning to kick things off, or it matches twice what it did on the last iteration. So it matches 1, then 2, then 4 and so on. Since these get added up, we're always one short of a power of 2, which we fix with the 1 at the end.
Due the trailing linefeed, the match is simply removed from the input.

QBIC, 26 18 bytes
Thank you, @DLosc, for saving 8 bytes!
≈q*2<=:|q=q*2]?a-q

Explanation
≈     |  WHILE
 q*2       q doubled (this doesn't actually double q, but evaluates 2q)
    <=     is less than or equal to
      :    the input number (cmd line param, variable 'a')
q=q*2      double q (2, 4, 8, ...)
]          WEND
?a-q       PRINT a - q (ie 100 - 64 = 36)

Mathematica, 21 17 bytes
#-2^Floor@Log2@#&

Try it online!
This is my first Mathematica answer, feel free to tell me what have I screwed up.
-4 bytes thanks to @HyperNeutrino!
So as it turns out, someone made a similar program before, and sent it to the OEIS. However, keep in mind that the floor of a logarithm is basically defined as the number of digits of a number. This is just a coincidence, or rather a task simple enough that many people will get the same answer.

The () is apparently unnecessary

17 bytes

17 bytes: #-2^⌊Log2@#⌋&

@Jenny_mathy Someone came up with the same exact program? I didn't know this was a sequence in OEIS

Too bad we can't do #~BitClear~-1& which would be 14 bytes.  Seems like the natural extension of the syntax.  Maybe in version 12.

@KellyLowder Could you explain that syntax?

@NieDzejkob, Assuming you're OK with the infix notation, the idea would be that the -1 rolls around to the other side of the list of bits (the most significant side), like Part[x,-1] takes from the right of the list while Part[x,1] takes from the left.  Many other functions use this convention such as Take, Drop, Span.  Since BitClear only accepts integers this would cause no problems.

@KellyLowder no, I see how negative numbers should wrap around. I don't see how this makes Mathematica do BitClear[#,-1]

@NieDzejkob, well do you agree that BitClear[#,BitLength@#-1]& gives the correct answer?  I'm saying the syntax should allow the BitLength@# to be omitted.

Let us continue this discussion in chat.

APL (Dyalog Unicode), 9 bytes
⊢-2*∘⌊2⍟⊢

Try it online!
-1 byte thanks to Adam

Completely correct, although I would have used TIO to generate a template for me. Anyway, ⊢-2*∘⌊2⍟⊢ saves a byte.

I was sad that APL wasn't represented, and there is was, almost lost in the scroll!  I miss APL.

@cmm APL is alive and well. Feel free to hang out in the Stack Exchange APL chat room.

Pyth, 5 bytes
a^2sl

Test suite.
Explanation:
    l   Log base 2 of input.
   s    Cast ^ to integer (this is the position of the most significant bit.)
 ^2     Raise 2 to ^ (get the value of said bit)
a       Subtract ^ from input

Alice, 8 bytes
./-l
o@i

Try it online!
Explanation
.   Duplicate an implicit zero at the bottom of the stack. Does nothing.
/   Switch to Ordinal mode, move SE.
i   Read all input as a string.
l   Convert to lower case (does nothing, because the input doesn't contain letters).
i   Try reading all input again, pushes an empty string.
/   Switch to Cardinal mode, move W.
.   Duplicate. Since we're in Cardinal mode, this tries to duplicate an integer.
    To get an integer, the empty string is discarded implicitly and the input is
    converted to the integer value it represents. Therefore, at the end of this,
    we get two copies of the integer value that was input.
l   Clear lower bits. This sets all bits except the MSB to zero.
-   Subtract. By subtracting the MSB from the input, we set it to zero. We could
    also use XOR here.
/   Switch to Ordinal, move NW (and immediately reflect to SW).
o   Implicitly convert the result to a string and print it.
/   Switch to Ordinal, move S.
@   Terminate the program.

Japt, 6 bytes
^2p¢ÊÉ

Try it online!
Explanation
^2p¢ÊÉ
   ¢     Get binary form of input
    Ê    Get length of that
     É   Subtract 1
 2p      Raise 2 to the power of that
^        XOR with the input

If input 1 can fail: 4 bytes
¢Ån2

Try it online!
Explanation: get input binary (¢), slice off first char (Å), parse as binary back to a number (n2).

Octave, 20 bytes
@(x)x-2^fix(log2(x))

Try it online!

PARI/GP, 18 bytes
n->n-2^logint(n,2)

Alternate solution:
n->n-2^exponent(n)

The first one seems to give wrong answers. Should it be n->n-2^logint(n,2)? The second one is not supported in my version of PARI/GP, nor in the version used by tio.run. Is that a new function?

@JeppeStigNielsen Oops, fixed -- that's what I get for submitting from my phone. Yes, the second one is a new function.

@JeppeStigNielsen I just checked, exponent was added 5 days ago, compared to this challenge which was added yesterday. :)

Haskell, 32 29 bytes
(!1)
x!y|2*y>x=x-y|z<-2*y=x!z

Try it online!
-3 bytes thanks to @Laikoni
Older solution, 32 bytes
f x=last[x-2^i|i<-[0..x],2^i<=x]

Try it online!

Anonymous functions are allowed, so you don't need the f= in the first variant. Additionally z<-2*y=x!z saves a byte: Try it online!

Julia, 24 bytes
n->n-2^length(bin(n))÷2

Try it online!
Int(floor(log2(n))) is too long.

Welcome to PPCG! :)

Ruby, 31 bytes
->n{(0..n).find{|i|n-i&n+~i<1}}

Another bit-twiddling approach, might work better in a language where 0 is falsey. Finds the smallest number i such that n-i is a power of two, using the property of powers of two that they're the only numbers with no 1 bits in common with their predecessors.

Japt, 6 4 bytes
ì2_Å

Try it or run all test cases
ì2_Å     :Implicit input of integer
ì2       :Convert to base 2 digit array
  _      :Pass through the following function and convert back to decimal
   Å     :  Slice off the first digit

Befunge, 22 bytes
&:1\v\*2\<
$%.@>2/:#^_

Try it online!
Explanation
Befunge doesn't have bit manipulation instructions, but we can instead use the mod command (%) to mask out the bits that we want to keep. So basically we calculate n % 2b, where b is the number of bits in the number minus one.
&:              Read n from stdin and make a copy to work with.
  1\            Push the initial mask value below it on the stack.

    v           Start a loop to determine the number of bits to mask.
    >2/         Divide the copy of n by 2.
       :#^_     Check if it has become zero.
        \<      If not, turn back and swap the mask value to the top of the stack.
      *2        Multiply the mask value by 2.
     \          Swap the modified copy of n back to the top of the stack.
    ^           Repeat the loop.

$               Once the copy of n becomes zero, we can exit the loop and drop it.
 %              We can then mod the original n with the mask value to get the result.
  .@            Finally output the result and exit.

REXX, 52 bytes
b=x2b(d2x(arg(1)))
parse var b '1' b
say x2d(b2x(b))

Explanation:

Convert argument 1 into hex, then into binary representation.
Use parse to find first '1' in b, then store the rest of the string in b again.
Convert b into hex, then into decimal.

an explanation would be nice

Consider it done.

IA-32 machine code, 12 bytes
Hexdump:
91 0f bd c8 33 d2 42 d3 e2 33 c2 c3

Corresponding assembly code, with inline disassembly:
91          xchg eax, ecx;
0f bd c8    bsr ecx, eax;
33 d2       xor edx, edx;
42          inc edx;
d3 e2       shl edx, cl;
33 c2       xor eax, edx;
c3          ret;

Motorola 68020 Assembler, Unknown byte count, possibly 8
BFFFO D0{31:32}, D1 # Scan D0 from MSB to LSB, looking for the first set bit,
                    # from bit 31 for 32 bits
                    # Store this in D1
BCLR  D1, D0        # Clear the D1'th bit in D0

It's been a long time since I've done 680x0 assembler, and I can't find an online simulator.
This takes a 32-bit input in D0, and returns it from there. It also trashes D1. Flags are also changed.
Bad things will happen if D0 is zero; but the rules exclude that possibility.

16F48A Microcontroller, 155 bytes
IN Q,s0
MOVI s0,s1
MOVI s2,00
MOVI s3, 09

A: INC s2
SHR s1
JNZ A

B: DEC s3
DEC s1
JNZ B

C: MOVI s3,s4
SHL s0
DEC s3
JNZ C

D: DEC s4
SHR s0
JNZ D
OUT s0

explanation:
This particular microcontroller takes inputs in binary, starting at the top of the code and working its way down. It can only use 9 registers (s0 through s8, but cannot output s8) and each of those registers can store 8 bits - again, in binary.
The first section takes the input and sets some values for later use.
section A shifts the input right, effectively removing bytes at the end, until it reaches zero, all the while, s2 is keeping track of how many shifts have taken place.
Section B then takes the amount of right shifts from 9, to determine how many times to shift left until the front byte that is a 1 has been removed.
Section C actually shifts left, but saves the amount of shifts to be able to shift right again.
Finally, section D shifts it right, to move it to the original position, minus the first 1.

Often assembly submissions are rated in the size of their assembled machine code output (which usually results in a way better score ;-) )

@MatteoItalia that's something I'm going to look into then!

J, 8 Bytes
#.@}.@#:

How it works:
  @  @       | Verb conjunction. Makes sure it isn’t executed as a hook
      #:     | Converts Number to binary, with no leading 0s (except if arg is 0)
   }.        | Drop leading 1
#.           | Convert back to int

Works for 1 and 0 since #. will convert an empty array into 0

Vyxal, 3 bytes
bḢB

Try it Online!
Explained
bḢB
b   # binary
 Ḣ  # remove first item
  B # binary back to base 10

Ruby, 22 bytes
->n{n^1<<Math.log2(n)}

Try it online!

Bash, 27 bytes
bc -l<<<"$1-2^(l($1)/l(2))"

Try it online!

PowerShell, 66 62 bytes
($c=[Convert])::ToInt32(0+($c::ToString("$args",2)|% su* 1),2)

Try it online!
Thanks to cogumel0 for -4 bytes.
Does exactly what it says on the tin. Takes input $args, converts it toString, replaces the leading 1 using System.substring, then converts it back toInt32. Output is implicit.
Yay for lengthy .NET calls.

Using the mathematical method that others are using, we can get down to
PowerShell, 59 56 bytes
param($a)$a-($m=[math])::pow(2,$m::floor($m::log($a,2)))

Try it online!
Thanks to cogumel0 for -3 bytes.
This takes input $a, takes the log in base 2, then floors that. The floor is needed because if we simply cast to an integer, PowerShell does Banker's Rounding which could lead to erroneous results. Then we take 2 to that power, and subtract that from $a. Output is implicit.

You can get down to 48 bytes actually: $m=[math];$_-$m::pow(2,$m::floor($m::log($_,2)))

@cogumel0 That's using $_ for input, which I consider to be a snippet and not a function or program. The $m=[math] trick is pretty clever, though, thanks!

Both filters and functions allow access to $_. But filters only have a Process block making them ideal for these scenarios. If you consider a function to be acceptable than so would a filter, and therefore this code is valid ;)

You can also save a few more bytes on the first one too though: 61 bytes (even if you use $args instead of $_): $c=[Convert];$c::ToInt32(0+($c::ToString($args,2)|% su* 1),2). It uses string.Substring() instead of -replace, which shortens it somewhat. It does however need the 0+ to account for cases where the string has a length of 1 before you remove the first character (less bytes than doing [int])

But if using a filter, we'd need to have filter listed, which is going to be more bytes yet. Thanks for the substring idea, though, even though quotes around $args brings it up to 62.

Pyth, 6 bytes
it.BQ2

Try it online!

-1 bytes

Actually, 7 bytes
;╘L2ⁿ@-

Try it online!

05AB1E, 7 bytes
bS1¸-JC

Try it online! or Try all test cases
b       # Convert to binary
 S      # Split
  1¸-   # Subtract 1 from the first element
     JC # Join and convert to decimal

b¦C works except for an input of 1

The logarithm version is a bit shorter, too bad we need to handle 1 though :(, otherwise the 3-byter would be the shortest

@Mr.Xcoder the answer that you've linked doesn't look like it's using logarithms. However, the formula n-2^floor(log2(n)) handles 1 correctly, if that's what you are referring to

@NieDzejkob The answer I linked to is my own answer and does use logarithms.

@Mr.Xcoder then the StackExchange app is utterly broken, let me see

C# (.NET Core), 28+13=41 35 bytes
n=>n-(1<<(int)System.Math.Log(n,2))

Try it online!
Acknowledgements
All credit for this answer goes to NieDzejkob; the mathematical approach is significantly better than binary string manipulation (below).
-6 bytes thanks @raznagul for seeing that System could just be included directly in the code, rather than as using System;.
C# (.NET Core), 86+13=99 bytes
n=>{var t=Convert.ToString(n,2).Remove(0,1);return t.Length<1?0:Convert.ToInt32(t,2);}

Try it online!
+13 bytes for using System;
UnGolfed
n=>{
    var t = Convert.ToString(n,2).Remove(0,1);
    return t.Length < 1 ? 0
                        : Convert.ToInt32(t,2);
}

Unfortunately Convert.ToInt32 throws an exception on "", instead of returning 0.

Well, there's a better way

“unfortunately” … err.

@KonradRudolph "unfortunately" in the sense that it stops me having a shorter answer :-P. Probably "fortunate" in every other use.

In the mathematical approach you can directly write System.Math.Log... and remove the using-Statement.

Octave, 26 bytes
@(x)bi2de(de2bi(x)(2:end))

Try it online!
Note: The TIO-link uses dec2bin and bin2dec instead of de2bi and bi2de, because the communications package is not installed. The code works fine on Octave-online.net.
Explanation:
@(x)                        % Anonymous function that takes a decimal number x as input
    bi2de(                  % Convert the following to decimal:
          de2bi(x)            % Convert x to decimal
                  (2:end)     % And take all elements except the first
                         )  % That's it.

Perl 6, 17 bytes
{$_+&+^(1+<.msb)}

Try it online!

$_ is the argument to the function.
+& is the bitwise AND operator.
+^ is the bitwise NOT operator.
+< is the bitwise left shift operator.
.msb returns the most significant bit of the function argument.

C (gcc), 37 + 2 (-lm) = 39 bytes
f(x){x-=pow(2,floor(log(x)/log(2)));}

Try it online!
Saved some bytes thanks to a tip pointed out by @JustinMariner! This is my first proper C golf :-)
Since there is no plain log2 built-in in C, I just (ab)used the fact that loge(x) / loge(2) = ln(x) / ln(2) = log2(x).

C (gcc), 34 bytes
f(c){c-=c^1<<31-__builtin_clz(c);}

Try it online!

I think you can save some bytes by using this tip: Try it online!

Add++,  24  14 bytes
D,f,@,BBEP2$Bb

Try it online!
How it works
D,f,@,   - Create a monadic function.
         - Example argument:   10
      BB - To binary; STACK = [[1 0 1 0]]
      EP - Dequeue;   STACK = [[0 1 0]]
      2  - Push 2;    STACK = [[0 1 0] 2]
      $  - Swap;      STACK = [2 [0 1 0]]
      Bb - From base; STACK = [2]

CJam - 8 bytes
ri2b(;2b

Explanation
ri    # Reads input as integer
2b    # Convertion to base 2
(;    # Removes first element
2b    # Convertion from base 2

You can replace (;2 with ().

@MartinEnder Thanks, great idea

Brain-Flak, 44 bytes
<>(()){((({}{}))){<>({}[()])}{}}<>([{}]{}<>)

Try it online!
Explanation
The bulk of the modulus program is {(({})){<>({}[()])}{}}, which decrements two counters and resets the base counter every time it reaches zero.  To deal with powers of two, the counter needs to be doubled each time it resets.  The obvious way to do that is by replacing (({})) with ((({}){})), but this won't work since the doubling happens before the first iteration.
Instead, ((({}{}))) pushes the initial counter an additional time, and then adds these two copies together in the next iteration.  In the first iteration, a 1 and an implicit 0 are added together to start with 1 as desired.

Batch, 62 bytes
@set/an=%2+%2+1
@if %1 gtr %n% %0 %1 %n%
@cmd/cset/a%1-n/2-1

Edged out this 63-byte attempt:
@set/an=%2+%2+1,m=%1^^n+1
@if %m% gtr %n% %0 %1 %n%
@echo %m%

Which itself edged out this 64-byte port:
@set n=1
:l
@if %1 geq %n% set/an*=2&goto l
@cmd/cset/a%1-n/2

Funky, 23 20 bytes
n=>n~1<<math.log(2n)

I'm quite pleased with the result of this one.
Firstly, this calculates math.floor(math.log(2,n)) incrementing a variable i whilst dividing n by two until it is <1. Then, get's two to the power of that value, which removes all but the most significant bit from n. We can then get the answer by xoring this with n, which in funky is done with ~.
Turns out the Javascript method works for this too, although math.log2 can be replaced with math.log(2, because 2 and n are seen as two separate tokens in Funky, and thus is parsed like 2, n
Try it online!

PHP, 28 25+1 bytes
<?=$argn^1<<log($argn,2);

Run as pipe with -nF or try it online.

-4 bytes by replacing &~ with ^.

@ColeraSu -3 bytes. +1 is for -F. But thanks.

C 35 bytes
N;f(n){for(N=n;n&n-1;)n&=n-1;N-=n;}

Try it online!

n&=n-1

Does the opposite of the problem statement, it clears the least significant bit.
I have a vague memory of there being a similar trick for most significant bit from seeing it on coding game but may remember wrong.
Recursive function, 45 43 bytes
N;g(n){n&=(N=n&~-n)?g(N):n;}f(n){N=n-g(n);}

Try it online!
cleblancs code shortened to 34 bytes
i=1;f(n){for(;n/i/2;i*=2);n-=n^i;}

Try it online!
28 bytes, possibly cheating , using pointer instead of return

f(*n){*n^=1<<(int)log2(*n);}

Try it on ideone! , doesn't work on tio.run

PHP, 38 bytes
<?=bindec(substr(decbin($argv[1]),1));

Straightforward way to do it. Convert the input to binary, remove the first character of the "string", convert back to decimal.
Try it online!

Jq 1.5, 19 bytes
.-pow(2;log2|floor)

This is just a jq version of the formula n - 2^Floor[Log2[n]] from OEIS A053645
Try it online!

Common Lisp, 40 bytes
(lambda(n)(- n(expt 2(floor(log n 2)))))

Try it online!

Python, 32 bytes
lambda n:n-2**(n.bit_length()-1)

Hello, and welcome to our site! There are a few things that this is missing. First off, you'll need to provide a byte count, which in this case is 25. But unfortunately, this breaks two of our standard rules: 1) This assumes that the input is stored in n, and 2) this simply evaluates to the answer rather than printing/returning it. You could fix this by taking input from STDIN (n=input();print(n-2**...) or by wrapping this in a function (def f(n):return n-2**... or lambda n:n-2**..., which is probably the best option).

Also, you could remove the spaces around the minus sign: n-2**(n.bit_length()-1) to save 2 bytes.

@DJMcMayhem thanks for the courteous pointers.  appreciate the gentle schooling

SNOBOL4 (CSNOBOL4), 74 65 bytes
	I =INPUT
	J =1
R	J =GE(I - J) J + J :S(R)
	OUTPUT =I - J / 2
END

Try it online!
	I =INPUT			;*read in input
	J =1				;*set J to 1
R	J =GE(I - J) J + J :S(R)	;*if I-J>=0, double J and repeat, otherwise
	OUTPUT =I - J / 2		;*output I-J/2
END

Python 2, 30 bytes
f=lambda n:n-1and 2*f(n/2)+n%2

Try it online!
Uses no built-in methods. 3 bytes longer than this solution using bin.

Pip, 8 bytes
FB+@>TBa

Try it online!
Explanation
     TBa  Convert cmdline arg to binary
   @>     Take all but the leftmost character
  +       Convert to number (required for turning "" into 0 so FB works properly)
FB        Convert from binary to decimal

Manufactoria, 24 Bytes, 3 Blocks
c12:6f3;c12:8f3;p12:7f2;

?lvl=32&code=c12:6f3;c12:8f3;p12:7f2;&ctm=Level_Name!;Level_description!;:*;5;3;0;

JavaScript (ES6), 23 bytes
f=x=>x^1&&f(x/2)*2|x&1

Not the shortest JS solution overall, but it beats the .toString(2) solution.

Perl 5, 23 + 1 (-p) = 24 bytes
$_-=2**int((log)/log 2)

Try it online!

GolfScript - 13 bytes
~2base(;2base

Explanation
~      # Parse argument
2base  # Convertion to base 2
(;     # Cut away first byte
2base  # Convertion from base 2

Tcl, 45 bytes
puts [scan [regsub 1 [format %b $argv] 0] %b]

Try it online!

C++, 63 bytes
[](decltype(0ul)x){auto y=x;return x^_BitScanReverse(&y,x)<<y;}

Usage (works in MS Visual Studio):
#include <intrin.h>
#include <stdio.h>

int main()
{
    auto h = [](decltype(0ul)x){auto y=x;return x^_BitScanReverse(&y,x)<<y;};

    printf("%d\n", h(10));
}

I added an artificial constraint on my code:

It must use _BitScanReverse

The effect this had on my code is quite severe.

I used decltype(0ul) as an euphemism for unsigned long.
_BitScanReverse outputs its result by pointer, so I had to declare another unsigned long variable. This time, I did it with auto y=x.
The output of _BitScanReverse is "whether the input is nonzero", which is 1 (luckily).
The returned expression modifies y and then uses it, which is Undefined Behavior. There are no warnings though, and it works correctly.

ARM (Thumb mode) machine code, 12 bytes
b0 fa 80 f1 01 31 88 40 c8 40 70 47

Disassembly:
fab0 f180       clz     r1, r0
3101            adds    r1, #1
4088            lsls    r0, r1
40c8            lsrs    r0, r1
4770            bx      lr

C++, 42 bytes
int f(int n){return n-exp2((int)log2(n));}

Could you provide a link to an online compiler where this works? I doubt this works without int n in the declaration, and I'm not sure that C++ has exp2 and log2 functions without some #include

Added the return type. About the includes, I don't see them counted in any of the previous C/C++ replies and I don't see you downvoting them or hassling them about it. But thanks anyway.

Oh I didn't downvote you! I'm sorry if you got that impression. That's due to a bug that sometimes hits new users with short posts. Which is really unfortunate, but SE seems to not care.

I see. No problem then.

In K&R C, any undeclared functions are assumed return an int, and take whatever type is passed in. Most modern compilers accept this, but create a warning. In golf we can make use of this.
However, in your submission, you marked it as C++, not C. C++ does not allow undeclared functions. Also you are passing an int into exp2 (and log2), which won't be promoted to float.
However, you can remove the int for the return and input for your function f - saving 8 bytes.
This should work, for 50 bytes, when split over two lines
#include<math.h> f(n){return n-exp2((int)log2(n));}

Pyth - 8 Bytes
ig.BQ2 2

Explanation:
ig.BQ2 2
i      2 Convert to base 2
 g   2   Slice from position 1 to the end (g slices from b-1)
  .B     Binary String representation of
    Q    Input

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
Bpb

Try it online!
Same strategy as every other golflang.

C (gcc), 27 bytes
Just realized this is a port of @xnor's python2 answer.
f(n){n=n>1?2*f(n/2)+n%2:0;}

Try it online!

Thunno 2, 5 bytes
ḃḣ0|Ḃ

Attempt This Online!
Explanation
ḃḣ0|Ḃ  # Implicit input      ->  100
ḃ      # Convert to binary   ->  "1100100"
 ḣ     # Remove first item   ->  "100100"
  0|   # Logical OR with 0   ->  "100100"
    Ḃ  # Convert to decimal  ->  36
       # Implicit output


text:
Minecraft Inventory Management
Minecraft inventory management is hard. You have 17 diamonds, but you need 7 to craft an enchantment table, a pickaxe, and a sword. Do you pick them up and right click 7 times? Or do you right click once and right click twice and take the 7 left? It's so confusing!
for those of you who are now confused, don't worry, I'll explain it all in a sec
Challenge
Given the size of a stack of items and a desired amount, determine the least number of clicks to get that amount. You only need to handle up to 64 for both inputs and you may assume you have infinite inventory slots. You cannot use the drag-to-distribute trick.
Definitions
The inventory is a collection of slots where you can store items.
A slot is a storage space in your inventory where you can place up to one type of item.
A stack is a number of items placed in the same group. For the purposes of this challenge, a stack is simply a bunch of items in the same place (so ignore stack-size)
The cursor is your pointy thingy. That cursor. It can have items "on it"; in other terms, if you clicked on a slot and picked up items, the items you picked up are "on the cursor" until you put them down.
Specifications
There are four possible situations. Either you have an item on your cursor or you don't, and either you left click or you right click.
If you don't have an item on your cursor and you left-click on a slot, you pick up the entire stack.
If you don't have an item on your cursor and you right-click on a slot, you pick up half the stack, rounded up.
If you have an item on your cursor and you left-click on a slot, you place all of the items into that slot. (For all you Minecraft players, you won't have >64 items for this challenge and they're all 64-stackable, and you only have one type so the item swap does not apply here)
If you have an item on your cursor and you right-click on a slot, you place one item into that slot.
So, you start with all of the items given (first input, or second; you may choose the order) in a slot, and you want to finish with having the desired amount (other input) in your cursor.
Let's run through an example. Say you start with 17 items and you want 7. First, you right-click on the stack, which means you have picked up 9 and there are 8 in that slot. Then, if you right-click on the stack again, you place one item back into the slot, leaving you with 8 and the slot with 9. Finally, you right-click again and you have 7 and the slot has 10. Thus, you would return 3 (the number of clicks).
If you manage to out-click-golf me, please tell me and I will edit the example :P
Test Cases
These are manually generated, so please tell me if there are any errors. I do inventory management through jitter-clicking right click so I don't have experience with optimal inventory management :P
Given, Desired -> Output
17, 7 -> 3
64, 8 -> 5
63, 8 -> 5
10, 10 -> 1
10, 0 -> 0 # note this case
25, 17 -> 7

Explanations
This challenge might be tricky for non-Minecraft players, I have no idea. Here are some explanations.
64, 8 -> 5 because you pick up 32 using right click, place it down, pick up 16, place it down, then pick up 8.
63, 8 -> 5 for the same reason.
25, 17 -> 7 because you pick up 13, place it down, pick up 6 from the leftover 12, place 2 back into the leftover stack, and then place the 4 in the cursor into the 13, and then pick those up.
Rules

Standard loopholes apply
You may assume that 0 <= desired <= given <= 64
You may take input in either order and do I/O in any reasonable format

http://ae-mod.info/

Related

So it's like a state-machine which starts with a state of 0,[n], may transition: (1) from 0,[a,b,...] to a,[b,...], b,[a,...], ceil(a/2),[floor(a/2),b,...], or ceil(b/2),[a,floor(b/2),...]; or (2) from x,[a,b,...] (x>0) to x-1,[a+1,b,...], x-1,[a,b+1,...], x-1,[a,b,...,1], 0,[a+x,b,...], 0,[a,b+x,...], 0,[a,b,...,x]. The challenge is then to find the minimum possible transitions from 0,[g] where g is the given to t,L where t is the desired target and L is any list?

C++, 498 482 457 bytes
If this function is just called once, it can be 455 bytes.
I found that almost every online GCC compilers (including TIO) forbids me to omit the type of the function f. However, the GCC on my computer allows that, and I don't know why.
This one can handle large inputs if a slot can contain that number of items (though needs a larger array and will probably run out of time).
#import<bits/stdc++.h>
#define t N.first
#define X n.erase(n.find
#define p(c){if(c==r)return l;if(L.emplace(w={n,c},l).second)Q[U++]=w;}
#define T(S,C)n.insert(S);p(C)X(S));
using m=std::multiset<int>;using s=std::pair<m,int>;s Q[99999];int x,l,B,U;int f(int a,int r){if(!r)return 0;std::map<s,int>L;s f({a},B=0),w,N;L[Q[U=1]=f];for(;;){l=L[N=Q[B++]]+1;x=N.second;t.insert(0);for(int i:t){m n=t;X(i));if(x){T(i+x,0)T(i+1,x-1)}if(!x&&i){p(i)T(i/2,i-i/2)}}}}

Ungolfed:
#include <map>
#include <set>
#include <queue>
#include <iostream>

using namespace std;

struct state {
    multiset<int> t; int q;
    bool operator<(const state& i) const { return make_pair(t, q) < make_pair(i.t, i.q); }
};

int f(int a, int target) {
    if (target == 0) return 0;

    map<state, int> len;
    queue<state> qu;
    state first = {{a}, 0};
    qu.push(first);
    len[first] = 0;

    #define push(c) { state a = {n, c}; auto t = len.insert({a, l + 1}); if (t.second) { \
        if (a.q == target) return l + 1; qu.push(a); \
    } } // push new state into queue and check for termination
    #define next(stk, cur) { n.insert(stk); push(cur); n.erase(n.find(stk)); }
    // insert new stack, push new state, erase the stack (for another use)

    while (qu.size()) { // BFS cycle
        state now = qu.front();
        qu.pop();

        int q = now.q;
        int l = len[now];

        multiset<int> n(now.t);
        for (int i : now.t) { // click on non-empty stack
            n.erase(n.find(i));
            if (!q) { // nothing on cursor
                push(i); // click left
                next(i / 2, (i + 1) / 2); // click right
            }
            else { // item on cursor
                next(i + q, 0); // click left
                next(i + 1, q - 1); // click right
            }
            n.insert(i);
        }
        if (q) { // click on empty stack
            next(q, 0); // click left
            next(1, q - 1); // click right
        }
    }
}

Jelly, 74 bytes
Ẏċ⁴¬
HĊ,$Ḟµ€1¦€F€;⁸Ḣ,$€
‘1¦€ṭ€⁹’¤
+1¦€⁹ṭ€0;ç
⁹Ȧ‘Ḥ¤ŀ
Ṫ;0ṙJ$çḢ
Wṭ0WÇ€Ẏ$ÑÐ¿L’

A full program with first input (3rd argument) the current stack and the second input (4th argument) the wanted cursor.
Try it online! Due to the implementation this hits the 60 second TIO time out for the 25, 17 test case. This may be remedied by removing the redundancies left in for golfiness using this 84 byter (which filters out zero-sized stacks and sorts those remaining with ḟ€Ṣ¥0¦€0 at the end of link 6 and only keeps unique states at each step with the use of Q$ in the Main link).
How?
The program implements the defined state-machine.
It creates the original state [0, [argument 1]]
then steps through to all the next possible states repeatedly
until one is found matching [argument 2, [...]].
Note: the program entry is at the "Main link" which is the bottommost one (Wṭ0WÇ€Ẏ$ÑÐ¿L’)
Ẏċ⁴¬ - Link 1, test a list of states for not having the desired cursor
Ẏ    - tighten by one
  ⁴  - program's fourth argument (second input) - desired cursor
 ċ   - count occurrences (the stack list will never match, so just inspecting the cursors)
   ¬ - logical negation

HĊ,$Ḟµ€1¦€F€;⁸Ḣ,$€ - Link 2, next states given a 0 cursor: list, rotatedStacks; number currentCursor (unused)
     µ€1¦€         - for each rotation of rotatedStacks apply to the first element:
H                  -   halve
   $               -   last two links as a monad
 Ċ                 -     ceiling
  ,                -     pair
    Ḟ              -   floor (vectorises) -- i.e. n -> [floor(ceil(n/2)),floor(n/2)]
                                                     = [ceil(n/2),floor(n/2)]
          F€       - flatten each -- i.e. each [[c1,f1],s2, s3,...] -> [c1,f1,s2,s3,...]
             ⁸     - chain's left argument, rotatedStacks
            ;      - concatenate -- i.e. [[c1,f1,s2,s3,...],[c2,f2,s3,...,s1],...,[s1,s2,s3,...],[s2,s3,...,s1],...]
                $€ - last two links as a monad for each:
              Ḣ    -   head
               ,   -   pair -- i.e. [c1,f1,s2,s3,...] -> [c1,[f1,s2,s3,...]]

‘1¦€ṭ€⁹’¤ - Link 3, next states given a non-0 cursor and a right-click: list, rotatedStacks; number currentCursor
 1¦€      - for each rotation of rotatedStacks apply to the first element:
‘         -   increment -- i.e. place an item into the first stack of each rotation
        ¤ - nilad followed by link(s) as a nilad:
      ⁹   -   chain's right argument -- currentCursor
       ’  -   decrement
    ṭ€    - tack each -- i.e. [s1-1,s2,s2,...] -> [currentCursor-1,[s1-1,s2,s2,...]]

+1¦€⁹ṭ€0;ç - Link 4, next states given a non-0 cursor: list, rotatedStacks; number currentCursor
 1¦€       - for each rotation of rotatedStacks apply to the first element:
    ⁹      -   chain's right argument -- currentCursor
+          -   add
     ṭ€0   - tack each to zero -- i.e. [s1+currentCursor,s2,s3,...] -> [0,[s1+currentCursor,s2,s3,...]]
         ç - call the last link (3) as a dyad -- get the right-click states
        ;  - concatenate

⁹Ȧ‘Ḥ¤ŀ - Link 5, next states: list, rotatedStacks; number currentCursor
     ŀ - call link at the given index as a dyad...
    ¤  -   nilad followed by link(s) as a nilad:
⁹      -     chain's right argument -- currentCursor
 Ȧ     -     any & all -- for our purposes zero if zero, one if not
  ‘    -     increment
   Ḥ   -     double
       - -- i.e. call link 2 if currentCursor is zero else call link 4

Ṫ;0ṙJ$çḢ - Link 6, next states: currentState  e.g. [cc, [s1, s2, s3, ...]]
Ṫ        - tail -- get the stacks, [s1, s2, s3, ...]
 ;0      - concatenate a zero - add an empty stack to the options for use
     $   - last two links as a monad for each:
    J    -   range(length)
   ṙ     -   rotate left by -- i.e. [[s2,s3,0,...,s1],[s3,0,...,s1,s2],[0,...,s1,s2,s3],[...,s1,s2,s3,0],...[s1,s2,s3,0,...]]
       Ḣ - head -- get the currentCursor, cc
      ç  - call the last link (5) as a dyad

Wṭ0WÇ€Ẏ$ÑÐ¿L’ - Main link: initialStack, requiredCursor
W             - wrap -- [initialStack]
 ṭ0           - tack to zero -- [0, [initialStack]]
   W          - wrap -- [[0, [initialStack]]]
         Ð¿   - loop while, collecting the results:
        Ñ     - ...condition: call next link (1) as a monad -- cursor not found
       $      - ...do: last two links as a monad:
    Ç€        -   call the last link (6) as a monad for each
      Ẏ       -   flatten the resulting list by one level
           L  - length
            ’ - decremented (the collect while loop keeps the input too)

source: Stack Exchange

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

sort: votes


text:
Paper and Envelope Sizes
Task
Given a letter (A, B, C), and a number (0-10), output the size of the matching standard paper size (Series A and B) or the matching standard envelope size (C series) in millimetres in the format aaaa x bbbb where aaaa and bbbb are the width and height measurements in millimetres as per ISO216 (Series A & B) or ISO296 (Series C)
To make things easier I will quote from Wikipedia's table of Paper Sizes
ISO paper sizes in portrait view
Format  A series    B series    C series
Size     mm × mm      mm × mm    mm × mm
0       841 × 1189  1000 × 1414 917 × 1297
1       594 × 841    707 × 1000 648 × 917
2       420 × 594    500 × 707  458 × 648
3       297 × 420    353 × 500  324 × 458
4       210 × 297    250 × 353  229 × 324
5       148 × 210    176 × 250  162 × 229
6       105 × 148    125 × 176  114 × 162
7        74 × 105     88 × 125   81 × 114
8        52 × 74      62 × 88    57 × 81
9        37 × 52      44 × 62    40 × 57
10       26 × 37      31 × 44    28 × 40

So examples of input and output:
**Test case 1**
Input: A4
Output: 210 x 297

**Test Case 2**
Input: B6
Output: 125 x 176

**Test Case 3**
Input: C2
Output: 458 x 648

Things to note:

The format "210 x 297" or "1000 x 1414" etc. While this is the preferable format, You can choose to omit the " x " from your output, i.e. in the form of an array or two numbers or whatever tickles your fancy as long as the width measurement is outputted before the height.
The ratio between the height and the width is roughly equivalent to the square root of 2, so in the calculation of the heights, the width is multiplied by sqrt(2), and then rounded up or down to the nearest millimetre, thus resulting in the measurements in the table above. This may help golf down your code.
In successive sizes for a series as you go down the table, the width for one size becomes the height for the next. This may also help you golf down your code.

Rules:

This is code-golf. Standard rules apply as a result. The score will be based on byte count. Lowest count will win.
No silly loopholes, we've been there before... We shan't go through this again.
If you can code it, then please also consider attaching a link to a working instance of your code so that other programmers and golfers can learn how your code works. This is not mandatory, but I'd like to encourage others to do this so we can all learn off one another. I certainly would love to learn more about other golfer's languages where possible.

Best of luck.

Bn is the geometric mean of An and An+1, and Cn is the geometric mean of An and Bn.

Let us continue this discussion in chat.

JavaScript (ES7), 57 bytes
Saved 1 byte thanks to @WallyWest
s=>n=>[n,n-1].map(x=>.707**x*{A:841,B:1e3,C:917}[s]+.2|0)

Nice work... you can make it 57 with s=>n=>[n,n-1].map(x=>.707**x*{A:841,B:1e3,C:917}[s]+.2|0) and it will still have the same precision in your output.

@WallyWest Thanks for the tip. I'd played around with various replacements for .7071 and .2 for a while and just kinda gave up when I found something that worked :P

No worries, all in the name of code golf... ;) I didn't realize map allowed one to reference unquoted keys within an object like that...? I'll have to use that sometime soon...

@WallyWest That has nothing to do with .map, you can use {key1:1,key2:2,key3:3}[myKey] anytime you wish. You only need to quote the keys if they are not valid variable names.

Brilliant, thanks for the tip...

C (gcc), 113 111 90 78 70 bytes
It needs -lm to run on TIO, but works well on my computer without the option.
Saved 20 bytes thanks to pizzapants184.
Return values by pointer.
f(a,b,c,d)int*c,*d;{float x=1e3*pow(.707,b+a%3/4.)+.2;*c=x,*d=x/.707;}

Explanation:
f(a,b,c,d)int*c,*d;{          // calling by char, but receive as int
    float x = 1e3 * pow(.707, // float gives enough precision
            a % 3 / 4.        // series: a%3/4.=.5,0,.25 when a=65,66,67
            + b) - .2;        // magic number to get correct roundings
    *c = x, *d = x / .707;
}

94 bytes + -lm by taking input as a char and int

91 bytes + -lm by changing (a^66?a^67:0.5:0.25:0) to abs(a-66)/(a-63.)

Java (OpenJDK 8), 59 bytes
f->s->new double[]{s=1e3*Math.pow(.707,s+f%3/4d)-.2,s/.707}

Try it online!
Inspired by @Colera Su's C entry, then improved by myself.

14 bytes saved thanks to Kevin Cruijssen

1000 can be 1e3.

75 bytes

Python 2, 103 97 93 84 83 81 bytes
def f(l,n):w=[841,1000,917][ord(l)-65];h=int(w/.707);exec"w,h=h/2,w;"*n;print w,h

Try it online!

APL (Dyalog), 31 28 bytes
-2 thanks to ngn.
Full program body. Assumes ⎕IO (Index Origin) to be 0, which is default on many systems. Prompts for number, then letter, both from STDIN. Prints to STDOUT.
⌊.2+1E3÷2*8÷⍨('BC'⍳⍞)+4×⎕-⍳2

Try it online!
A slightly modified version lets us test all possibilities at once: Try it online!
⍳2 first two ɩndices, i.e. 0 and 1
⎕- subtract that from numeric input
4× multiply four with that
(…)+ add the following
 ⍞ character input…
 'BC'⍳ …'s ɩndex in this string ("A" will give 2, as the index beyond the last)
8÷⍨ divide that by 8
2* raise 2 to the power of that
1E3÷ 1000 divided by that
.2+ add ⅕ to that
⌊ floor (round down)

Batch, 105 bytes
@set/aA=1189,B=1414,C=1297,h=%1,w=h*29/41
@for /l %%i in (1,1,%2)do @set/at=w,w=h/2,h=t
@echo %w% x %h%

41/29 ≅ √2

Are decimals not possible in Batch, @Neil? I would have thought h*.707 would be better than h*41/29? Mind you, ingenious use of approximation!

@WallyWest No, 32-bit signed integers only.

Oh, I see! Learn something new everyday!

MATL, 34 33 30 bytes
917 841 1000.5vjo)t2X^*hi2/W/k

Try it online! or Verify all test cases
Saved 4 byte thanks to Luis Mendo

JavaScript, 53 bytes
L=>N=>[N+1,N].map(p=>1091/2**(p/2+~{B:2,C:1}[L]/8)|0)

f=

L=>N=>[N+1,N].map(p=>1091/2**(p/2+~{B:2,C:1}[L]/8)|0)

document.write('

ABC',[...Array(11)].map((_,i)=>'
'+i+['A','B','C'].map(j=>''+f(j)(i)).join``).join``);

Save many bytes by using alternative output format, thanks to Neil.

66 bytes: L=>N=>(g=p=>1000.2/2**(N/2+p-{A:2,B:4,C:3}[L]/8)|0)(.5)+' x '+g(0)

Or 58 bytes if you use the alternative output format: L=>N=>[N+1,N].map(p=>1000.2/2**(p/2-{A:2,B:4,C:3}[L]/8)|0)

@Neil edited. And also reduced to 56 bytes

Befunge, 69 56 55 bytes
"}"8*~3%:"L"*7vv\p00-1_$..@
")"*":":-*!!\+<>2/00g:^:&\/

Try it online!
Explanation
We don't have the luxury of floating point or anything like a power function in Befunge, so we calculate the base size for the given format character, f, as follow:
fn = f % 3
width = 1000 - (n * 76 + 7) * !!n
height = width * 58 / 41

We then repeatedly rotate and divide these dimensions to get to the appropriate subdivision for the given size number.
"}"8*                         Push 1000 for later use in the width calculation.
     ~                        Read the format character from stdin.
      3%                      Convert into a number in the range 0 to 2.
        :"L"*7v               Calculate width = 1000 - (fn * 76 + 7) * !!fn
        -*!!\+<                  where fn is the format number derived above.
")"*":":                  /   Calculate height = width * 58 / 41.
                         \    Swap so the width is above the height on the stack.
                      v:&     Read the numeric size from stdin and duplicate for testing.
                      _       While not zero, go left.
                 p00-1        Decrement the size and move it from the stack into memory.
               v/             Swap the width and height.
               >2/            Divide the new width by 2.
                  00g:        Restore the size from memory and duplicate for testing.
                      _       While not zero, repeat this loop.
                       $      When zero, continue to the right and drop the size.
                        ..@   Output the width and height, then exit.

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


text:
Solve a matrix equation by Jacobi's method (Revised)
Mathematical Background
Let A be an N by N matrix of real numbers, b a vector of N real numbers and x a vector N unknown real numbers. A matrix equation is Ax = b.
Jacobi's method is as follows: decompose A = D + R, where D is the matrix of diagonals, and R is the remaining entries.
if you make an initial guess solution x0,  an improved solution is x1 = inverse(D) * (b - Rx) where all multiplications are matrix-vector multiplication and inverse(D) is the matrix inverse.

Problem Specification

Input: Your complete program should accept as input the following data: the matrix A, the vector b, an initial guess x0, and an 'error' number e.
Output: The program must output the minimum number of iterations such that the latest solution differs by the true solution, by at most e. This means each component of the vectors in absolute magnitude differ by at most e. You must use Jacobi's method for iterations.

How the data is inputted is your choice; it could be your own syntax on a command line, you could take input from a file, whatever you choose.
How the data is outputted is your choice; it can be written to a file, displayed in the command line, written as ASCII art, anything, as long as it is readable by a human.
Further Details
You are not given the true solution: how you calculate the true solution is up to you entirely. You may solve it by Cramer's rule for example, or computing an inverse directly. What matters is that you have a true solution to be able to compare to iterations.
Precision is an issue; some people's 'exact solutions' for comparison may differ. For the purposes of this code golf the exact solution must be true to 10 decimal places.
To be absolutely clear, if even one component of your present iteration solution exceeds its corresponding component in the true solution by e, then you need to keep iterating.
The upper limit to N varies based on what hardware you're using and how much time you're willing to spend running the program. For the purposes of this code golf, assume maximum N = 50.
Preconditions
When your program is called, you are free to assume that the following holds at all times:

N > 1 and N < 51, i.e. you will never be given a scalar equation, always a matrix equation.
All inputs are over the field of real numbers, and will never be complex.
The matrix A is always such that the method converges to the true solution, such that you can always find a number of iterations to minimise the error (as defined above) below or equal to e.
A is never the zero matrix or the identity matrix, i.e. there is one solution.

Test Cases
A = ((9, -2), (1, 3)), b = (3,4), x0 = (1,1), e = 0.04

The true solution is (0.586, 1.138). The first iteration gives x1 = (5/9, 1), differing by more than 0.04 from the true solution, by at least one component. Taking another iteration we find, x2 = (0.555, 1.148) which differs by less than 0.04 from (0.586, 1.138). Thus the output is
2

A = ((2, 3), (1, 4)), b = (2, -1), x0 = (2.7, -0.7), e = 1.0

In this case the true solution is (2.2, -0.8) and the initial guess x0 already has error less than e = 1.0, thus we output 0. That is, whenever you do not need to make an iteration, you simply output
0

Submission Assessment
This is code golf, with all standard loopholes hereby disallowed. The shortest correct complete program (or function), i.e. lowest number of bytes wins. It is discouraged to use things like Mathematica which wrap up a lot of the necessary steps into one function, but use any language you want.

You really should wait to get more feedback for it, especially given the recent closed post. PPCG challenges usually share common structure in specifications, what usually contribute to them being easy to understand, rather than tiresome and ambiguous. Try to look at some of the reasonably upvoted challenges and mimic the format.

@Uriel I realise this, but I feel I've been exhaustive in my specification, and the format while not exactly fitting the majority of questions, can be read linearly, and guide the reader accordingly. The format should also keep the content of the problem itself in mind.

Your test cases for example, are really hard to go through. We usually keep them in input - output plain format, in code blocks, with explanations following if contributing/necessary, but not interfering with verifying correctness

@Uriel Codeblocks is a good idea.

"The shortest correct complete program" sounds like you only allow programs and not functions. I'd add "/function".

+1 formatting makes or breaks my brain's ability to concentrate on a question

though it must be able to run without any further code -> so we can't call the function? The default for codegolf is to allow either a full program that takes input, for example, by STDIN or arguments, or to allow a function that can be called as passed the input, and would return or print the output.

@Stephen That's fine it's just I didn't want people writing a function in a language, and then needing more source code to run, e.g. in C++ excluding main().

@user1997744 Yup, makes sense. I believe the default is that any other code, like other functions or python imports, is allowed, but also included in the bytecount.

@user1997744 Some other notes: some users also propose that not all questions need to be sandboxed, for example this post and this post. After having posted that question, you had known what is considered "clear" and what is not on this site. Because the requirement is very strict, it is encouraged to use the sandbox if you think the question may be unclear or uninteresting.

@user202729 Right, and I deliberately did not use a sandbox to prove the point I can write a good question without it.

APL (Dyalog), 78 68 65 49 bytes
Exactly the type of problem APL was created for.
-3 thanks to Erik the Outgolfer. -11 thanks to ngn.
Anonymous infix function. Takes A b e as left argument and x as right argument. Prints result to STDOUT as vertical unary using 1 as tally marks, followed by 0 as punctuation. This means that even a 0-result can be seen, being no 1s before the 0.
{⎕←∨/e<|⍵-b⌹⊃A b e←⍺:⍺∇D+.×b-⍵+.×⍨A-⌹D←⌹A×=/¨⍳⍴A}

Try it online!
Explanation in reading order
Notice how the code reads very similarly to the problem specification:
{…} on the given A, b, and e, and and the given x,
 ⎕← print
 ∨/ whether there is any truth in the statement that
 e< e is smaller than
 |⍵- the absolute value of x minus
 b⌹ b matrix-divided by
 ⊃A b e the first of A, b, and e (i.e. A)
 ←⍺ which are the left argument
 : and if so,
  ⍺∇ recurse on
  D+.× D matrix-times
  b- b minus
  ⍵+.×⍨ x, matrix multiplied by
  A- A minus
  ⌹D the inverse of D (the remaining entries)
  ← where D is
  A× A where
  =/¨ there are equal
  ⍳ coordinates for
  ⍴A the shape of A (i.e. the diagonal)
Step-by-step explanation
The actual order of execution right-to-left:
{…} anonymous function where ⍺ is A b e and ⍵ is x:
 A b c←⍺ split left argument into A, b, and e
 ⊃ pick the first (A)
 b⌹ matrix division with b (gives true value of x)
 ⍵- differences between current values of x and those
 | absolute values
 e< acceptable error less than those?
 ∨/ true for any? (lit. OR reduction)
 ⎕← print that Boolean to STDOUT
 : and if so:
  ⍴A shape of A
  ⍳ matrix of that shape where each cell is its own coordinates
  =/¨ for each cell, is the vertical  and horizontal coordinates equal? (diagonal)
  A× multiply the cells of A with the that (extracts diagonal)
  ⌹ matrix inverse
  D← store in D (for Diagonal)
  ⌹ inverse (back to normal)
  A- subtract from A
  ⍵+.×⍨ matrix multiply (same thing as dot product, hence the .) that with x
  b- subtract that from b
  D+.× matrix product of D and that
  ⍺∇ apply this function with given A b e and that as new value of x

The output should be the number of iterations required for an accuracy of e.

-1: This is not a solution. You need x0 since the whole point is to know how many steps it takes to get to a desired accuracy from a particular starting point.

@user1997744 Ah, I misunderstood the problem. Sorry.

@user1997744 Better?

The output is 1 and 1 for the first. This requires a reader to perform an arithmetic operation to get the final answer. The second case should be 0, not nothing. I'm going to say this does fall under the 'display however you want to' rule I specified though, so I think this can just pass as a solution.

@user1997744 Not arithmetic operation, just ability to read unary, where indeed 0 is nothing.

65 bytes

extracting the diagonal from A with modified assignment is way too wasteful: D←0×A⋄(1 1⍉D)←1 1⍉A could be just D←A×=/¨⍳⍴A

@ngn Thanks. That lead to golfing an additional 5.

Python 3, 132 bytes
f=lambda A,b,x,e:e<l.norm(x-dot(l.inv(A),b))and 1+f(A,b,dot(l.inv(d(d(A))),b-dot(A-d(d(A)),x)),e)
from numpy import*
l=linalg
d=diag

Try it online!
Uses a recursive solution.

@Adám I'm not sure I quite understand. I interpreted it as f not having the name within the code block, which I have now fixed; however, if it is a different issue entirely, it may still be a problem.

@Adám That answer seems to corroborate what I currently have; it is a function with helper code that is capable of working as a unit after its definition.

Ah, ok. Never mind then. I don't know Python, so I was just curious. Good job!

Isn't the stopping criterion "This means each component of the vectors in absolute magnitude differ by at most e"? Basically the max-norm, not L2-norm.

@NikoNyrh Fixed.

R, 138 bytes
function(A,x,b,e){R=A-(D=diag(diag(A)))
g=solve(A,b)
if(norm(t(x-g),"M")<e)T=0
while(norm((y=solve(D)%*%(b-R%*%x))-g,"M")>e){T=T+1;x=y}
T}

Try it online!
thanks to NikoNyrh for fixing a bug
It's also worth noting that there is an R package, Rlinsolve that contains a lsolve.jacobi function, returning a list with x (the solution) and iter (the number of iterations required), but I'm not sure that it does the correct computations.

Isn't the stopping criterion "This means each component of the vectors in absolute magnitude differ by at most e"? Basically the max-norm, not L2-norm.

@NikoNyrh you are correct! fortunately, the norm function provides that for me as well for no additional bytes.

Clojure, 212 198 196 bytes
#(let[E(range)I(iterate(fn[X](map(fn[r b d](/(- b(apply +(map * r X)))d))(map assoc % E(repeat 0))%2(map nth % E)))%3)](count(for[x I :while(not-every?(fn[e](<(- %4)e %4))(map -(nth I 1e9)x))]x)))

Implemented without a matrix library, it iterates the process 1e9 times to get the correct answer. This wouldn't work on too ill-conditioned inputs but should work fine in practice.
Less golfed, I was quite happy with the expressions of R and D :) The first input % (A) has to be a vector, not a list so that assoc can be used.
(def f #(let[R(map assoc %(range)(repeat 0))
             D(map nth %(range))
             I(iterate(fn[X](map(fn[r x b d](/(- b(apply +(map * r x)))d))R(repeat X)%2 D))%3)]
          (->> I
               (take-while (fn[x](not-every?(fn[e](<(- %4)e %4))(map -(nth I 1e9)x))))
               count)))