title: Counting in binary nybbles

text:
# Question
Title: Counting in binary nybbles
This challenge is to output to your terminal, window, canvas or screen the numbers zero to 10 inclusive. Each outputted number must be shown as a 4-bit wide nybble, so zero must show as `0000` and so on.

You may separate each number outputted with a space, comma or carriage return. Smallest solution wins but the numbers can be displayed in any order you like as long as there are no repeating numbers in your sequence.

Entries in low-level binary languages need not worry about the comma or white space separators if it is not possible to output with commas or white spaces (i.e., the standard output is limited to binary only, or your solution is for an early computer kit such as the KIM-1 which has a limited digital display).

# Answer
# SmileBASIC, 26 bytes

```
FOR I=0TO&HA?BIN$(I,4)NEXT

```
> 2 votes

# Answer
# MATL, 6 bytes

```
0:10YB

```

Try it at **MATL Online**

**Explanation**

```
0:10    % Create the array [0...10]
YB      % Convert this array to a binary string where each number is
        % placed on a new row
        % Implicitly display the result

```
> 16 votes

# Answer
# 05AB1E, ~~9~~ 8 bytes

```
T         # push 10
 4ã       # cartesian product repeat with 4
   R      # reverse list
    T>£   # take the first 11 elements of the list
      »   # join by newline and display

```

Try it online!
> 15 votes

# Answer
## JavaScript, 46 bytes

```
for(i=15;i++<26;)alert(i.toString(2).slice(1))

```

Why use a padding function when you can simply add 16 to each number and slice off the first binary digit?
> 12 votes

# Answer
# Japt, 7 bytes

```
GôA,_¤Å

```

And here I was thinking Japt was doomed to be longer than every other golfing language...

Test it online!

### Explanation

```
GôA,_¤Å  // Implicit: A = 10, G = 16
GôA      // Create the inclusive range [G...G+A].
    _    // Map each item Z to Z
     ¤   //   .toString(2)
      Å  //   .slice(1).
         // Implicit: output result of last expression

```

Normally commas can be removed in Japt, but this one is there because of a bug: `_` normally means `function(Z){Z`, but for some reason the compiler thinks `A_` means `function(A,Z){Z`.
> 9 votes

# Answer
# Bash + GNU utils, 26

* 4 bytes saved thanks to @Dennis

```
seq -w 0 1010|sed /[2-9]/d

```

Try it online.
> 8 votes

# Answer
# Bash \+ Unix utilities, ~~29~~ 26 bytes

```
dc -e2o8927II^*8/p|fold -4

```

Try it online!

This is the same length as @DigitalTrauma/@Dennis's solution, but uses a completely different method.

Output is:

```
1010
0010
0110
0001
1001
0101
0100
0111
0011
1000
0000

```

(Any order is allowed.)

---

# Pure Bash, 34 bytes

```
echo 0{0,1}{0,1}{0,1} 10{00,01,10}

```

Try the pure Bash version online!

Output is:

```
0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010

```
> 7 votes

# Answer
# J, 6 bytes

```
#:i.11

```

Thanks to miles for cutting it down to 6 bytes!
> 7 votes

# Answer
# Python 3.6, ~~36~~ 35 bytes

```
i=11
while i:i-=1;print(f"{i:04b}")

```

-1 byte thanks to @JonathanAllan

### Python 3.5 and earlier:

```
i=11
while i:i-=1;print("{:04b}".format(i))

```

Try it online!
> 6 votes

# Answer
# Jelly, 7 bytes

```
2Bṗ4ṫ6Y

```

**Try it online!**

(5 bytes if trailing lines of nybbles are allowed, `2Bṗ4Y`)

### How?

Prints in descending order.

```
2Bṗ4ṫ6Y - Main link, no arguments
2B      - 2 converted to binary -> [1,0]
  ṗ4    - Cartesian 4th power -> [[1,1,1,1], [1,1,1,0], ..., [0,0,0,0]]
                            i.e.  16       , 15         ..., 0
    ṫ6  - tail from 6th item  -> [[1,0,1,0], [1,0,0,1], ..., [0,0,0,0]]
                            i.e.  10       , 9        , ..., 0
      Y - join with line feeds
        - implicit print

```

An alternative 7-byter is `2ṗ4Ịṫ6Y`, the `[1,0]` is replaced with `[1,2]` and  is the "is insignificant" monad (`abs(z)<=1`), converting `2`s to `0`s.
> 6 votes

# Answer
# CJam, 12 bytes

```
B{G+2b1>}%N*

```

Try it online!

### Explanation

The Cartesian power approach would have been my choice, but was already taken.

So this generates numbers from 0 to 10, and for each it adds 16 and converts to binary. Adding 16 ensures that the required leading zeros are produced, together with an extra leading one which is removed.

```
B             e# Push 11
 {      }%    e# Map over "11", implicitly converted to the array [0 1 ... 10]
  G+          e# Add 16. This makes sure there will be 5 binary digits: a leading 1
              e# which will have to be removed and the remaining, valid digits
    2b        e# Convert to array of binary digits
      1>      e# Remove first digit
          N*  e# Join by newlines. Implicitly converts arrays to strings

```
> 4 votes

# Answer
# PHP, 33 bytes

```
while($i<11)printf('%04b ',$i++);

```
> 4 votes

# Answer
# Intel 8080 machine code, MITS Altair 8800, 10 bytes

```
00 00 00 00 00 00 00 00 76

```

Listing:

```
0000   00   NOP
0001   00   NOP
0002   00   NOP
0003   00   NOP
0004   00   NOP
0005   00   NOP
0006   00   NOP
0007   00   NOP
0008   00   NOP
0009   00   NOP
000A   76   HLT

```

Uses the CPU's program counter (PC, aka instruction pointer) to count from 0 to 10 then halt. The output display is conveniently in nibble format already.

**Output:**

Output is displayed on Blinkenlights A3-A0.

Try it online!
> 4 votes

# Answer
# MATLAB / Octave, 13 bytes

```
dec2bin(0:10)

```

Online Demo
> 3 votes

# Answer
# Jelly, 8 bytes

```
2Ḷṗ4ḣ11Y

```

Try it online!

### How it works

```
2Ḷṗ4ḣ11Y  Main link.

2Ḷ        Unlength 2; yield [0, 1].
  ṗ4      Take the fourth Cartesian power.
    ḣ11   Head 11; discard all but the first eleven elements.
       Y  Join, separating by linefeeds.

```
> 3 votes

# Answer
# Jelly, ~~10, 9~~, 8 bytes

```
⁴r26BḊ€Y

```

Try it online!

I'm not that great at jelly, so I'd be open to any tips!

This uses Emigna's first algorithm

---

*Thanks to Dennis for ~~shaving off two bytes~~ making me tie his own answer. :P*

Explanation:

```
      Ḋ€    # Return all but the first element of each item in the list:
⁴r26        #   [16, 17, 18, ... 26]
     B      #   Converted to binary
        Y   # And joined with newlines

```
> 3 votes

# Answer
# Python 2, ~~38~~ 36 bytes

```
n=16;exec"print bin(n)[3:];n+=1;"*11

```

*Thanks to @DJMcMayhem for golfing off 2 bytes!*

Try it online!
> 3 votes

# Answer
# RProgN, 15 Bytes

```
~16.aL1{2B26q}:

```

~~This has been a *very* good modivation to add a `pad` function. The entirety of `]L4\-'0'\m\.`, more than half the code, is to pad.~~

\_Saved 6 bytes thanks to @ETHProductions, that's the pad function cut in half.

## Explained

```
~16.aL1{2B26q}:
~               # Zero Space Segment
 16.            # The literal number 16
    aL          # The length of the Alphabet
      1         # The literal number 1
       {     }: # For each number between 16 and 26 inclusive
        2B      # Convert to base 2
          26q   # Get the characters between 2 and 6 inclusive.

```

Try it online!
> 2 votes

# Answer
# BF, ~~121~~ 101 bytes

```
,....>,.<...+.>.<-..+.-.>.<..+..>.<-.+.-..>.<.+.-.+.>.<-.+..-.>.<.+...>.<.-...>.<+.-..+.>.<.-.+.-.!0

```

Requires a trailing newline. Makes use of `!` symbol (so, check the box that says `!`) with this interpreter (try it online!).

Potentially 51 bytes if each operator was considered as 4 bits
> 2 votes

# Answer
# Retina, ~~36~~ 33 bytes

```

%%%%
+`(^|\b)%
0$%'¶$%`1
11!`\d+

```

Try it online!

**Explanation**

```

%%%%
```

Replace the empty (non-existent) input with `%%%%`.

```
+`(^|\b)%
0$%'¶$%`1

```

On the first run of this stage, it will match `^%` and essentially replace the text `%%%%` with the two lines `0%%%` and `1%%%`. The stage will loop until the output stops changing. On the second run, it will match `\b%` (since digits count as word characters and `%` doesn't), and replace the groups by duplicating them and adding `0` to one copy and `1` to the other: `0%%%` becomes the lines `00%%` and `01%%` (and the same sort of thing for `1%%%`). Through this loop all 16 bitstrings will be produced, linefeed separated.

```
11!`\d+

```

The first 11 matches of `\d+` (a run of at least 1 digit) are retrieved. The matches are output in a linefeed-separated list.
> 2 votes

# Answer
## C ~~170~~ 120 bytes

```
n,i,m,k[4]={0};f(){for(m=0;m<=10;m++){n=m;i=0;for(;n;i++){k[i]=n;n/=2;}for(i=4;i>0;i--)printf("%d",k[i-1]%2);puts("");}}

```

Ungolfed version:

```
void f()
{
    int n,i,m,k[4]={0};

   for(m=0;m<=10;m++)
   {
      n=m;
      i=0;

      for(;n;i++)
      {
         k[i]=n;
         n/=2;
      }
      for(i=4;i>0;i--)
         printf("%d",k[i-1]%2);

      puts("");
   }
}

```

Can definitely be shortened!?

@Ahemone Awesome idea, Thanks!

Should work now! Try it online!
> 2 votes

# Answer
## Ruby, 25 bytes

```
11.times{|n|puts"%04b"%n}

```
> 2 votes

# Answer
# C, ~~75~~ ~~68~~ 69 bytes

**Approach 1: ~~75~~ ~~73~~ ~~74~~ bytes**

```
m;p(i){putchar(i?m&i?49:48:9);}r(){for(m=11;m--;p(4),p(2),p(1),p(0))p(8);}

```

Try it online!

---

**Approach 2: ~~68~~ 69 bytes**

```
m,n,o;f(){for(m=11;m--;)for(n=m,o=5;o--;n*=2)putchar(o?n&8?49:48:9);}

```

Try it online!
> 2 votes

# Answer
## C#, 96 bytes

---

**Golfed**

```
()=>{for(int i=0;i++<11;)System.Console.WriteLine(System.Convert.ToString(i,2).PadLeft(4,'0'));}

```

---

**Ungolfed**

```
() => {
    for( int i = 0; i++ < 1; )
        System.Console.WriteLine( System.Convert.ToString( i, 2 ).PadLeft( 4, '0' ) );
}

```

---

**Full code**

```
using System;

namespace Namespace {
    class Program {
        static void Main( string[] args ) {
            m();

            Console.ReadLine();
        }

        static void m() {
            for( Int32 i = 0; i++ < 11; )
                Console.WriteLine(
                    Convert.ToString( i, 2 ). // Converts the number to binary code
                    PadLeft( 4, '0' ) );      // Fills the number with the missing '0's
        }
    }
}

```

---

**Releases**

* **v1.0** \- `96 bytes` \- Initial solution.
> 2 votes

# Answer
## R - 23

We can use `intToBin` function from the **`R.utils`** package:

```
R.utils::intToBin(0:10)

[1] "0000" "0001" "0010" "0011" "0100" "0101" "0110" "0111" "1000" "1001" "1010"

```
> 2 votes

# Answer
# C, 68 bytes

```
f(){puts("0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010");}

```

Somehow, this is the shortest C answer so far…

EDIT: I was missing `1000` somehow. Well, it’s still winning.
> 2 votes

# Answer
# Commodore VIC-20/VC-20/C64 - 95 69 68 67 tokenized BASIC bytes used (obfuscated and minimized)

```
0dEfnb(x)=sgn(xandb):fOi=0to10:b=8:fOj=0to3:?rI(stR(fnb(i)),1);:b=b/2:nE:?:nE

```

Copy and paste the above text into WinVice, for instance. Just about fits onto 80 characters on a Commodore 64.

Here's the non-obfuscated symbolic listing for illustrative purposes:

```
0 DEF FN B(X)=SGN(X AND B)
1 FOR I=0 TO 10
2  LET B=8
3  FOR J=0 TO 3
4   PRINT RIGHT$(STR$(FN B(I)),1);
5   LET B=B/2
6  NEXT J
7  PRINT
8 NEXT I

```

Of course this may be minimised and further obfuscated. Explanation:

The `DEF FN` command in line zero is a simple function which accepts one numeric parameter. This will give the algebraic sign the number passed to it as a parameter, in this case is `AND`ed with the value `B` (declared elsewhere, but becomes global once declared).

Line 1 starts the loop counter `I`

Line 2 sets the value of the 3rd BIT.

Line 3 starts loop counter `J` (we want bits 0 - 3 essentially).

Line 4 gets the `STR$` value (string value) of the function `FN B(I)`, this is then passed to the `RIGHT$` command as CBM BASIC auto-pads outputted numbers with a white space, so we get the last character in the string created by `STR$`.

Line 5 moves the BIT counter down one (like `x >> 1` in C I suppose).

Line 6 moves the `J` loop up one.

Line 7 prints a new line (line `echo PHP_EOL;` in PHP).

Line 8 moves the `I` loop up one.

I've 'nested' the listing in the example to better show the loop and loop order.
> 2 votes

# Answer
# Python 2, 44 bytes

```
for x in range(11):print bin(x)[2:].zfill(4)

```

This uses the `zfill` function which works like `rjust` except it always padds with `0` so you don't waste bytes on an argument.
> 1 votes

# Answer
## Pyke, 8 bytes

```
TFw0+b2t

```

Try it here!

```
TFw0+b2t - for i in range(10):
  w0+    -    i+16
     b2  -   bin(^)
       t -  ^[:-1]

```

Also 8 bytes:

```
TF 4@b2t

```

Try it here!

```
   4@    - set_bit(4, i)

```
> 1 votes

# Answer
## Ruby, 38 bytes

```
11.times{|i|puts i.to_s(2).rjust 4,?0}

```
> 1 votes

# Answer
# Pyth - ~~8~~ 7 bytes

```
<5^_`T4

```

Try it online here.
> 1 votes

# Answer
# stacked, 30 bytes

```
11:>[2 baserep'0'4 pad out]map

```

Try it online!

`11:>` is a range from `0` to `10`. The rest is rather self-explanatory.

Other solutions that I've found:

```
11:>[bits 4 dpad''join out]map
11:>[bits 4 dpad$tostrmap]map out
11~>15+[bits behead''join out]map
16 26|>[bits behead''join out]map

```
> 1 votes

# Answer
# BF, 134 bytes

I'm sure this can be shortened--it's pretty much my first BF golf.

```
++++++++++[>+>+>+++++>>>+++++>>>+++++>>>+++++[<<<]>>>-]>>+>[-->>+>]<<<[<<<]>>[>[>>-[<<+.->]<[>]>-[<<.>]<[>]>++>]<-[<<<-]++<<[<<<]>.>-]

```

Try it online! Assumes a tape infinite in both directions, like the interpreter at TIO uses. An interpreter where `<` at the left end of the tape is a no-op would save three bytes.

### Explanation

More than half of the code (the first 77 bytes, to be precise) is spent initializing the tape. The steps go like this:

```
++++++++++
10|

[>+>+>+++++>>>+++++>>>+++++>>>+++++[<<<]>>>-]
 0|10|10|50| 0| 0|50| 0| 0|50| 0| 0|50|

>>+>[-->>+>]<<<[<<<]>>
 0|10|11|48| 0| 1|48| 0| 1|48| 0| 1|48| 0| 1|

```

The cells initialized to `1` store the bits of our number plus 1: `1` represents a zero bit and `2` represents a one bit.

The initialization phase ended with the pointer on the `11`. Now we use this cell to run 11 iterations of our loop:

```
[>          Move to the first 48
 [>>-       While we're still on a 48, move 2 cells over and decrement
  [         The cell's value now equals the bit it represents; if it's not 0:
   <<+.-    Move to the 48, increment, output, and decrement again
   >        Move to the next cell, which holds a 0
  ]         Leave the loop
  <[>]>     Pointer shenanigans to get back on the cell representing the bit
  -         Decrement again: cell is 255 for a zero bit, 0 for a one bit
  [         If cell is not 0:
   <<.>     Move to the 48, output, and move to the 0 cell
  ]
  <[>]>++   Get back on the bit's cell; increment back to original value
  >         Move to the next 48
 ]          Loop exits once we've output all four bits
            Now we increment the binary number: a one bit turns into a zero bit and
            carries; a zero bit turns into a one bit and doesn't carry
 <-         Move back to the rightmost bit cell and decrement
 [          If it is not 0, it must represent a one
  <<<-      Leave it decremented, go to the next bit cell and decrement it too
 ]          Loop exits on a bit cell that represented a zero
 ++         Increment it twice (to represent a one)
 <<[<<<]    Move back to first cell on tape
 >.         Move to 10 cell and output (newline)
 >-         Move to loop counter cell and decrement
]

```
> 1 votes

# Answer
## C, 110? bytes

```
n,i,m,k[4]={0};f(){for(m=-1;(n=++m)<11;i=0){for(;n;n>>=1)k[i++]=n;for(i=4;i--;)printf("%d",k[i]&1);puts("");}}

```

Ungolfed:

```
int f() {
    int n,i,m,k[4]={0};
    for(m=-1;(n=++m)<11;i=0) {
        for(;n;n>>=1)
            k[i++]=n;
        for(i=4;i--;)
            printf("%d",k[i]&1);
        puts("");
    }
}

```
> 1 votes

# Answer
## Common Lisp, ~~41~~ ~~39~~ ~~34~~ 32

*2+5=7 bytes removed thanks to PrzemysławP.*

I am using the `FORMAT` function function, for printing a number as binary with padding and separators, called with the magic number 8800979740570 (a.k.a. 8012345679A in base 16):

```
CL-USER> (format t"~,,,4:b"8800979740570)
1000,0000,0001,0010,0011,0100,0101,0110,0111,1001,1010

```

I used to do the same with *123456789A*, but as noted by *PrzemysławP*, the order does not matter and we can save some bytes. This is because with the original order, the leading zeros would be done as padding and would not be separated into groups of 4 digits; here, by starting with *1000*, we don't need any padding. In addition to that, I also removed the *mincol* argument (53) because I don't need to specify the size of the number anymore.

## Formatted output of integers

The documentation for format (see above) is detailed for `~D` (decimal base) but the same applies to other ones (hex `~X`, binary `~B`, octal `~O`, custom `~R`). Note that for floats there are other arguments.

The most general format is `~mincol,padchar,commachar,commaintervalD`, but note that the two last arguments, *commachar* and *commainterval* are only meaningful if `D` has a colon-modifier `:D`, which by default separate digits by groups of 3 (*commainterval* is a custom value, instead of 3), inserting the *commachar* character between such groups, by default a comma.

The *mincol* argument is one that is found in other format directives and specifies the horizontal space allocated for the thing being printed. When the actual size required is smaller, a padding might be applied (left or right, or both for some directives). The padding fills the remaining space with *padchar*, a character. When the actual size is bigger, the layout might not be pretty but the object is printed fully.

More precisely (from the above link):

> `~D` Decimal. An arg, which should be an integer, is printed in decimal radix. `~D` will never put a decimal point after the number. `~mincolD` uses a column width of *mincol*; spaces are inserted on the left if the number requires fewer than *mincol* columns for its digits and sign. If the number doesn't fit in *mincol* columns, additional columns are used as needed.
>
> `~mincol,padcharD` uses *padchar* as the pad character instead of space.
>
> The @ modifier causes the number's sign to be printed always; the default is to print it only if the number is negative.
>
> The : modifier causes commas to be printed between groups of three digits
>
> the third prefix parameter may be used to change the character used as the comma. Thus the most general form of ~D is ~mincol,padchar,commacharD.
>
> *X3J13 voted in March 1988 (FORMAT-COMMA-INTERVAL)* to add a fourth parameter, the commainterval. This must be an integer; if it is not provided, it defaults to 3. This parameter controls the number of digits in each group separated by the commachar.
>
> By extension, each of the ~B, ~O, and ~X directives accepts a commainterval as a fourth parameter, and the ~R directive accepts a commainterval as its fifth parameter.

### Padding and separators

Note that the padding characters are not grouped, as explained above. For example, the zeros in front of the numbers are not separated:

```
 CL-USER> (format t "~10,'0:d" 12345)
 000012,345

```

... there is no easy way to combine format parameters to output:

```
 000,012,345

```

... that's why I first added the zeros and a comma explicitly in the answer. This is not necessary anymore.
> 1 votes

# Answer
# SAS, 39 bytes

Not very creative...

```
data t;do i=0 to 10;put i binary4.;end;

```
> 1 votes

# Answer
## Ruby, 44 bytes

`(0..10).each{|e|puts (16+e).to_s(2)[-4..-1]}`
> 1 votes

# Answer
# Common Lisp, 41 bytes

```
(dotimes(i 11)(format t"~5,,,'0<~B ~>"i))

```

Different method than other CL submission.
> 1 votes

# Answer
# ***Perl 6, ~~25~~ 22 bytes***

```
printf "%04b "x 11,^11

```

Fairly similar to the ruby answer. EDIT: Saved 3 bytes by removing parantheses.
> 1 votes

# Answer
# Java 8, 195 bytes

```
interface C{static void main(String[]a){for(int i=0;i++<11;)System.out.println(((java.util.function.Function<String,String>)x->("0000"+x).substring(x.length())).apply(Integer.toString(i-1,2)));}}

```

I am never golfing in Java again...

-2 bytes thanks to ceilingcat
> 1 votes

# Answer
## REXX, 32 bytes

```
do i=0 to 10
  say x2b(d2x(i))
  end

```
> 1 votes

# Answer
# Japt, 6 bytes

```
Aò¤ù'0

```

Test it

```
Aò¤ù'0
A          :10
 ò         :Range [0,A]
  ¤        :Convert each to binary
   ù       :left pad each to length of longest
    '0     :  With "0"

```
> 1 votes

# Answer
# Haskell, 92 bytes

```
0#_="";b#n=(if even$n`div`b then"0"else"1")++(div b 2#n)
main=putStr.unwords.map(8#)$[0..10]

```

Try it online!
> 1 votes

# Answer
Java 8, 77 bytes

```
()->{for(int i=43;i>=0;i--)System.out.print(((i/4>>i%4)&1)+(i%4==0?" ":""));}

```

For each number, print one bit at a time by bit shifting then masking with &1.
> 1 votes

# Answer
# Perl 5, 22 bytes

```
printf'%04b 'x11,0..10

```

Try it online!
> 1 votes

# Answer
# Rust, 37 bytes

```
||for i in 0..11{print!("{:04b} ",i)}

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 57 bytes

```
: f 11. do 4. do j 3 i - rshift 2 mod 1 .r loop cr loop ;

```

Try it online!

### Explanation

* Loop from 0 to 10 (inclusive)
    + For each iteration:
    + Loop from 0 to 3, print the character at that index (with no space)
    + Print a newline

### Code Explanation

```
: f                 \ start a new word definition
  11.               \ place 11 and 0 on stack
  do                \ loop from 0 to 10
    4.              \ place 4 and 0 on the stack
    do              \ loop from 0 to 3
      j             \ place outer loop index (current number) on stack
      3 i -         \ get the position of the digit we care about
      rshift 2 mod  \ get the value at that position
      1 .r          \ print the binary digit with no space appended
    loop            \ end the inner loop
    cr              \ print a newline
  loop              \ end the outer loop
;                   \ end the word definition

```
> 1 votes

# Answer
# MathGolf, 9 bytes

```
Ar☻+mÅà╞n

```

Try it online.

**Explanation:**

```
Ar        # Push a list in the range [0,11): [0,1,2,3,4,5,6,7,8,9,10]
  ☻+      # Add 16 to each: [16,17,18,19,20,21,22,23,24,25,26]
    m     # Map each value to,
     Å    # using the following two commands:
      à   #  Convert the value to a binary string
       ╞  #  And remove the first digit
    n     # After the map: join the list by newlines
          # (after which the entire stack joined together is output implicitly)

```

The first four bytes could alternatively be `A╒E+`:

```
A╒        # Push a list in the range [1,11]: [1,2,3,4,5,6,7,8,9,10,11]
  E+      # Add 15 to each: [16,17,18,19,20,21,22,23,24,25,26]

```
> 1 votes

# Answer
# x86-16, IBM PC DOS, 28 bytes

Binary (build `NIB.COM` with `xxd -r`):

```
00000000: b30a 53b1 04d2 e3b8 000e d0d3 1430 cd10  ..S..........0..
00000010: e2f5 b820 0ecd 105b 4b79 e7c3            ... ...[Ky..

```

Unassembled listing:

```
B3 0A       MOV  BL, 10         ; set initial counter
        NIB_LOOP:
53          PUSH BX             ; save counter in BX
B1 04       MOV  CL, 4          ; shift / loop 4 times
D2 E3       SHL  BL, CL         ; shift left one nibble/nybble
        BIT_LOOP:
B8 0E00     MOV  AX, 0E00H      ; BIOS write to console / zero AL
D0 D3       RCL  BL, 1          ; rotate left one bit, MSB into carry
14 30       ADC  AL, '0'        ; add carry bit to '0' ASCII char
CD 10       INT  10H            ; write to console
E2 F5       LOOP BIT_LOOP       ; keep looping to next bit
B8 0E20     MOV  AX, 0E20H      ; BIOS write to console / space
CD 10       INT  10H            ; write to console
5B          POP  BX             ; restore counter
4B          DEC  BX             ; is >= 0?
79 E7       JNS  NIB_LOOP       ; if so, keep looping
C3          RET                 ; exit to DOS

```

### Output

Standalone PC DOS executable .COM program. Output is to console, descending separated by spaces.
> 1 votes

# Answer
# Wren, ~~107~~ 106 bytes

```
for(i in[0,1])for(j in[0,1])for(k in[0,1])[0,1].each{|l|
System.printAll([i,j,k,l])
if(i==1&&k==1)Fn.x()
}

```

Try it online!

## Explanation

```
for(i in[0,1])for(j in[0,1])for(k in[0,1])[0,1].each{|l| // Define all those binary digits
System.printAll([i,j,k,l])                                // Print all the binary digits
if(i==1&&k==1)                                            // If the number has reached 10,
              Fn.x()                                      // Execute an undefined command in the Fn class
                                                          // That breaks out of all of the 4 for loops and stops the program
}

```
> 1 votes

# Answer
# Vyxal `Rj`, 38 bits<sup>v2</sup>, 4.75 bytes

```
₀ƛΠṅ∷

```

Try it Online!

Bitstring:

```
10101010010101010011110101110100101100

```

VYXAL FOREVER RAHHHHH

```
₀ƛΠṅ∷
₀      # push 10
 ƛ     # map over the range [0,10] (R flag)
  Π    # binary string
   ṅ   # padded to length 8
    ∷  # second half

```

Created with the help of Luminespire.
> 1 votes

---
Tags: code-golf, kolmogorov-complexity, binary
---


title: Convert to Spoken Binary

text:
# Question
Title: Convert to Spoken Binary
# Introduction

In the video the best way to count, binary is proposed as the best system of counting numbers. Along with this argument is a proposal on how to say numbers in this system. First, we give names to each "double power of two", \\$2^{2^n}\\$ for each \\$n\\$.

```
number = symbol = spoken
============================
2^0    = 1      = "one"
2^1    = 2      = "two"
2^2    = 4      = "four"
2^4    = H      = "hex"
2^8    = B      = "byte"
2^16   = S      = "short"
2^32   = I      = "int"
2^64   = L      = "long"
2^128  = O      = "overlong"
2^256  = P      = "byteplex"

```

Then, to get from a number to its spoken binary, we

1. Take its (big-endian) bit string and break off bits from the end equal to the number of zeros in the largest double power of two less than or equal to the number.
2. Use the name for the corresponding double power of two in the middle, and recursively name the left and right parts through the same procedure. If the left part is one, it is not spoken, and if the right part is zero, it is not spoken.

This system is similar to how we normally read numbers: 2004 -\> 2 "thousand" 004 -\> "two thousand four".

For example, 44 in binary is `101100`. Split at four bits from the end and insert "hex", meaning \\$2^4\\$: `10` "hex" `1100`. `10` becomes "two" and `1100` splits into `11` "four" `00`, or "two one four". So the final number is "two hex two one four" or `2H214` in symbols (note that this is not the recommended way of writing numbers, just speaking).

As a longer example, we have one thousand:

```
1111101000
11 B 11101000
2 1 B 1110 H 1000
2 1 B 11 4 10 H 10 4 00
2 1 B 2 1 4 2 H 2 4

```

# Challenge

Your program must take a positive integer \\$n\\$ as input and output the string of symbols for the spoken binary of that number.

While numbers under \\$2^{512}\\$ are expressible in this system, you only need to handle integers **up to and including** \\$2^{32}\\$ = `I`, and as such, do not need to consider `L`, `O`, or `P`.

Standard loopholes are forbidden. As this is , shortest program wins.

# Example Input and Output

```
1 -> 1
2 -> 2
3 -> 21
4 -> 4
5 -> 41
6 -> 42
7 -> 421
8 -> 24
9 -> 241
10 -> 242
11 -> 2421
12 -> 214
25 -> H241
44 -> 2H214
100 -> 42H4
1000 -> 21B2142H24
4294967295 -> 21421H21421B21421H21421S21421H21421B21421H21421
4294967296 -> I

```

# Answer
# Jelly, ~~36~~ 29 bytes

```
BUḟ€0“24HBSI”s2jœr1ɗẎḊḢ$?€ɗƒU

```

Try it online!

A full program that takes a single positive integer argument and prints the spoken binary form to STDOUT.

## Explanation

```
BUḟ€0“24HBSI”s2jœr1ɗẎḊḢ$?€ɗƒU
B                             # Convert to binary
 U                            # Reverse
  ḟ€0                         # Filter out 0 from each
     “24HBSI”             ɗƒ  # Starting with this, reduce using each character in "24HBSI" as the right argument in turn and the following:
             s2               # - Split into pieces of length 2
                         €    # - For each piece:
                     ḊḢ$?     #   - If length 2 and the second part is non-empty:
               j              #     - Join with the relevant character
                œr1           #     - Trim 1s from the end
                    Ẏ         #   - Else: join outer lists
                            U # Reverse order of final string (and implicit smashing print)

```

Created with the help of Luminespire.
> 3 votes

# Answer
# Charcoal, ~~42~~ 41 bytes

```
≔⁻Ｉ⮌↨Ｎ²0θＦ24HBSI≔Ｅ⪪θ²⪫⮌ＥΦκ∨μ¬ν⎇∧ν⁼μ1ωμιθθ

```

Try it online! Link is to verbose version of code. Supports numbers from `1` to `18446744073709551615`. Explanation:

```
≔⁻Ｉ⮌↨Ｎ²0θ

```

Convert the input to a list of `1`s and empty strings according to the reverse of its binary representation.

```
Ｆ24HBSI

```

Loop over the additional possible "digits".

```
≔Ｅ⪪θ²⪫⮌ＥΦκ∨μ¬ν⎇∧ν⁼μ1ωμιθ

```

Group the existing digit blocks into pairs, then for each pair, create a new digit block by removing any second part if it is zero, or making it the empty string if it is one, switching the parts, and joining on the next digit.

```
θ

```

Output the final result.
> 3 votes

# Answer
# JavaScript (Node.js), ~~84 79~~ 77 bytes

```
f=(n,k=6,y=1,u=2**2**--k)=>n<y?'':~k?f(n/u,k,2)+['24HBSI'[n<u||k]]+f(n%u,k):1

```

Try it online!

Your 232-1 case seems wrong
> 2 votes

# Answer
# , 129 bytes

```
\(x,`~`=paste0)Reduce(\(y,z)apply(matrix(y,2),2,\(w)gsub("^0*[1"~z~"]|0","",w[1]~z~w[2])),c(2,4,"H","B","S","I"),x%/%2^(63:0)%%2)

```

Attempt This Online!

An R translation (more-or-less) of my Jelly answer. A function that takes a single positive integer and returns the spoken binary form as a string.
> 2 votes

# Answer
# Jelly, 42 bytes

```
l2l2Ḟ
WµÇ2*2*⁸d⁹jɗ×nJaƲ¹Ƈ)F$ÐLÇ»-ị“4HBSI12

```

A full program that accepts a positive integer and prints the spoken binary.

**Try it online!** Or see the test-suite.

### How?

```
l2l2Ḟ - Link 1: integer, X -> floor(X log 2 log 2)
          Note when X = 1 l2l2 -> (-inf + nan j) and Ḟ takes the real part -> -inf

WµÇ2*2*⁸d⁹jɗ×nJaƲ¹Ƈ)F$ÐLÇ»-ị“4HBSI12 - Main Link: positive integer P
W                                    - wrap P in a list
                      ÐL             - apply while distinct:
                     $               -   last two links as a monad - f(Current):
 µ                 )                 -     for each {V in Current}:
  Ç                                  -       call Link 1 -> floor(V log 2 log 2)
   2*                                -       2 exponentiate {that}
     2*                              -       2 exponentiate {that}
                                               -> value of the digit to use, say D
       ⁸    ɗ                        -       last three links as a dyad - f(V, D):
         ⁹                           -         D
        d                            -         {V} div-mod {D}
          j                          -         join {that} with {D}
                Ʋ                    -       last four links as a monad - f(Parts=that):
              J                      -         indices {Parts} -> [1,2,3]
             n                       -         {Parts} not equal {that} (vectorises)
            ×                        -         {Parts} multiply {that} (vectorises)
               a                     -         {that} logical AND {Parts}
                 ¹Ƈ                  -       keep truthy values
                    F                -     flatten
                        Ç            - call Link 1 (vectorises)
                         »-          - max with -1 (convert -inf to -1)
                           ị“4HBSI12 - index into (1-based & modular) "4HBSI12"
                                     - implicit print

```
> 1 votes

# Answer
# Haskell, 115 bytes

```
p=[2^2^i|i<-[6,5..0]]
c=concat
f x=c[c[f y|y>1]++c[[l]|y>0]|(l,n,m)<-zip3"ISBH421"p$tail p++[1],y<-[mod x n`div`m]]

```

Try it online!
> 1 votes

---
Tags: code-golf, number, binary
---


title: Stackin' Boards

text:
# Question
Title: Stackin' Boards
I have a bunch of boards I need to stack in as small a space as possible. Unfortunately, the boards fall over if I stack them more than 10 high. I need a program to tell me how to stack the boards to take as little horizontal space as possible, without stacking boards more than ten high, or having boards hanging out over empty space.

## Your Task:

Write a program or function, that when given an array containing the lengths of boards, outputs as ASCII art the way to stack the boards to conserve as much horizontal space as possible, without stacking the boards more than 10 high or having any part of any board hanging out over empty space. Your ASCII art should show the configuration of the boards, with each one shown using a different character. There will be a maximum of 20 boards. For example, if the input was \[2,2,4,2,2,4,4,4\], a possible output is:

```
dhh
dgg
dff
dee
abc
abc
abc
abc

```

which is a stable configuration (although this would fall over in ~0.1 seconds in real life).

## Input:

An array containing up to 20 integers, showing the lengths of the boards.

## Output:

ASCII art showing the configurations of the boards, as outlined above.

## Test Cases:

Note that there may be other solutions for the test cases, and the characters shown for each board may be different.

```
[12,2,2,2,3,4,4,8,8]        -> ffgghhiii
                               ddddeeeeeeee
                               bbbbbbbbcccc
                               aaaaaaaaaaaa

[4,4,4,4,4,4,4,4,4,4,4,4]   -> llll
                               aaaa
                               cfghk
                               cfghk
                               cfghk
                               cfghk
                               debij
                               debij
                               debij
                               debij

[4,4,4,4,4,4,3,3,3,2,2,2,1] -> jjml
                               iiil
                               hhhk
                               gggk
                               ffff
                               eeee
                               dddd
                               cccc
                               bbbb
                               aaaa

```

## Scoring:

This is , lowest score in bytes wins

# Answer
# Python 3, 513 512 511 509 499 497 485 465 459 458 444 bytes

Incredibly bad runtime, will finish at some point

```
e,j,c=enumerate,len,range
def f(n,p=[],o=97):
    r,l,m=lambda x:min(b,f(n[:i]+n[i+1:],x,o+1),key=j),chr(o),j(p)
    b=[p,l*(sum(n)*2+m)][n>[]]
    for i,a in e(n):
        for h,d in e(p):
            if a<11-j(d):b=r([p[f]+l*a*(f==h)for f in c(m)])
            if(j(d)<10)*all(j(x)==j(d)for x in p[h:h+a])*(a<=m-h):b=r([p[f]+l*(h<=f<h+a)for f in c(m)])
        if a<11:b=r(p+[l*a])
        b=r(p+[l]*a)
    return["\n".join("".join(9-u<j(x)and x[9-u]or" "for x in b)for u in c(10)),b][o>97]

```

Try it online!

Edit: -2 -8 bytes thanks to @Mr. Xcoder Edit: -8 bytes thanks to @notjagan

## Explanation

```
e,j,c=enumerate,len,range
         # These built-ins are used a lot
def f(n,p=[],o=97):
         # n is the remaining blocks
         # p is the current stack
         # o is the ASCI code for the next letter to use
    r,l,m=lambda x:min(b,f(n[:i]+n[i+1:],x,o+1),key=j),chr(o),j(p)
         # r is the recursive call, that also selects the smallest stack found
         # l is the letter to use next
         # m is the length of the current stack
    b=[p,l*(sum(n)*2+m)][n>[]]
         # Sets the current best, if there are no remaining blocks, select the found stack, else we set it to be worse than the possible worst case
    for i,a in e(n):
         # Loop through all the remaining blocks
        for h,d in e(p):
         # Loop through all the columns in the current stack
            if a<11-j(d):b=r([p[f]+l*a*(f==h)for f in c(m)])
         # If we can place the current block vertically in the current column, try it
            if(j(d)<10)*all(j(x)==j(d)for x in p[h:h+a])*(a<=m-h):b=r([p[f]+l*(h<=f<h+a)for f in c(m)])
         # If we can place the current block horizontally starting in the current column, try it
        if a<11:b=r(p+[l*a])
         # If the current block is lower than 10, try place it vertically to the right of the current stack
        b=r(p+[l]*a)
         # Try to place the current horizontally to the right of the current stack
    return["\n".join("".join(9-u<j(x)and x[9-u]or" "for x in b)for u in c(10)),b][o>97]
         # Return the best choice if we aren't in the first call to the function, that is the next letter is a. Else return the found best option formatted as a string

```

# Python 3, 587 bytes

Actually runnable on TIO for some of the test cases

```
e,j,c=enumerate,len,range
def f(n,p=[],o=97,b=[]):
    if(not n):return p
    if not b:b="a"*sum(n)*2
    r,q,s,l,m=lambda x:q(f(n[:i]+n[i+1:],x,o+1,b)),lambda x:[b,x][j(b)>j(x)],b,chr(o),j(p)
    if j(b)<=m:return b
    for i,a in e(n):
        for h,d in e(p):
            if a<11-j(d):b=r([p[f]+l*a*(f==h)for f in c(m)])
            if j(d)<10 and a<=m-h and all(map(lambda x:j(x)==j(d),p[h:h+a])):b=r([p[f]+l*(h<=f<h+a)for f in c(m)])
        if s==b:
            if a<11and m+1<j(b):b=r(p[:]+[l*a])
            if m+a<j(b):b=r(p[:]+[l for r in c(a)])
    return["\n".join("".join(map(lambda x:" "if u>=j(x)else x[u],b))for u in c(9,-1,-1)),b][o>97]

```

Try it online!

Both solutions could probably be golfed quite a bit.
> 3 votes

# Answer
# Python3, 1081 bytes

Rather long, but crunches every test case, including several additional ones, in ~0.184 seconds

```
E=enumerate
R=range
from itertools import*
G=lambda l:[[j for j,_ in b]for a,b in groupby(E(l),key=lambda x:x[1]=='')if a]
def C(l,L,H):
 q=[([a],[i])for i,a in E(l)if a<=L]
 while q:
  A,I=q.pop(0)
  if sum(A)<=L and(H==0 or sum(A)==L):yield(tuple(A),I)
  for i,a in E(l[max(I)+1:],max(I)+1):
   if sum(T:=A+[a])<=L:q+=[(T,I+[i])]
def P(b,l,Q,t):
 for i,a in E(b):
  if''in a:
   F=0
   B,Y=eval(str(b)),[]
   for g in G(a):
    if(O:=[*C(l,len(g),t)]):
     F,d=1,{}
     for J,K in O:d[J]=K
     O=[*d.items()]
     M=max(sum(A)for A,_ in O)
     V,I=min([(o,p)for o,p in O if sum(o)==M],key=lambda x:len(x[0]));Y+=I
     for v in V:
      Q+=1
      for _ in R(v):B[i][g.pop(0)]=chr(Q)
   if F or t:return(B,[y for x,y in E(l)if x not in Y],Q)
def f(l):
 I,Q=1 if max(l)<11 else max(l),96
 while I:
  q,S=[(B:=[[''for _ in R(I)]for _ in R(10)],[*l],96)],[B]
  while q:
   b,L,Q=q.pop(0)
   if[]==L:return b
   if(C:=P(b,L,Q,1))and C not in S:q+=[C];S+=[C]
   if(C:=P([*map(list,zip(*b))],L,Q,0)):
    B,L,Q=C;
    if(B:=[*map(list,zip(*B))])not in S:q+=[(B,L,Q)];S+=[B]
  I+=1

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Stably sort N elements in this restricted "cmov" language
The following problem is taken from the real world — but indubitably `code-golf`! In this puzzle, the programming language is fixed, and your job is to write the most efficient program in this fixed language. The language has no loops; a program is a straight-line sequence of instructions. Each instruction consists of exactly three characters — an opcode and two operands — and in fact there are only four possible opcodes:

* `<xy` — Compare the value in register *x* to the value in register *y*; set *flag* = L if *x* \< *y*; *flag* = G if *x* \> *y*; and *flag* = Z otherwise.
* `mxy` — Set the value in register *x* equal to the value in register *y*. (This is "move.")
* `lxy` — If *flag* = L, then set the value in register *x* equal to the value in register *y*; otherwise do nothing. (This is "conditional move," or "cmov".)
* `gxy` — If *flag* = G, then set the value in register *x* equal to the value in register *y*; otherwise do nothing. (This is "conditional move," or "cmov".)

For example, the program `mca <ba lcb` means "Set register *c* equal to the minimum of *a* and *b*."

The program `mty <zy lyz lzt` means "Stably sort the values in registers *y* and *z*." That is, it sets *y* to the minimum of *y* and *z* (breaking ties in favor of *y*) and sets *z* to the maximum of *y* and *z* (breaking ties in favor of *z*).

The following 16-instruction program stably sorts the values in registers *x, y, z*:

```
<zy mtz lzy lyt
max mby mcz
<yx lay lbx
<zx lcx lbz
mxa myb mzc

```

**Your task is to find the shortest program that stably sorts *four* registers *w, x, y, z*.**

A trivial Python implementation is available here if you want to test your solution before (or after) posting it.

# Answer
# 21 instr

```
  '<wx', 'gtw', 'gwx', 'gxt',
  '<xy', 'guy', 'gyx', 'gxu',
  '<yz', 'gtz', 'gzy', 'gyt',
  '<wx',        'gxw', 'gwu',
  '<xy',        'gyx', 'gxt',
  '<wx',        'gxw', 'gwt'

```

Try it online!

---

Neil suggests that reordering into this may get more clear:

```
<wx gtw gwx gxt
<xy gty gyx gxt
<wx     gxw gwt
<yz gtz gzy gyt
<xy     gyx gxt
<wx     gxw gwt

```

This looks more like insertion sort

---

---

For large enough amount of element, a \\$\tilde {\mathrm O} \left(n\right)\\$ sorting algorithm exist. Here I construct a \\$\mathrm O \left(n \log^2 n\right)\\$ one using a \\$\mathrm O \left(n \log n\right)\\$ sorting network, which seems reducible: (say the input is `A[0..n-1]`

1. Set `O` to `min(A)` and `I` to `max(A)`.

Notice that if `O = I`, then all elements are equal, and no swap would apply.

2. Let `B[i][j] = i & (1 << j) ? I : O` for `0 <= j < log2(n)`.
3. Do sorting network on `A`, each element `A[i]` together with `B[i]`.

To do a multi-element compare:

```
T = O
if (P[0] < Q[0]) T = I
if (P[1] > Q[1]) T = O
if (P[1] < Q[1]) T = I
if (P[2] > Q[2]) T = O
if (P[2] < Q[2]) T = I
...
if (P[9] > Q[9]) T = O
if (P[9] < Q[9]) T = I
if (T > O) swap

```

This makes a swap in \\$\mathrm O \left( \log n\right)\\$
> 6 votes

# Answer
## ~~23~~ 22 instructions

Here's a different approach from l4m2's bubble sort — we can use insertion sort. We start by sorting *x, y, z*. Then we insert *w* in its proper place by starting at the top and working downward: If *w \> z*, insert it and bump out the old *z* into *q*. If *w \> y*, insert *q* and bump out the old *y* into *q*. And so on. An "unoptimized" sequence of instructions that works for that second part is:

```
mpw mtx muy mvz
<vp mqp lqv lvp
mau <up luq lqa
<tp lpt ltq
mwp mxt myu mzv

```

I can optimize that and append it to ~~l4m2's 12~~ Neil's 11-instruction `sort3` to produce this ~~23~~ 22-instruction `sort4`:

```
<zy lty lyz lzt
<yx ltx lxy lyt
<zy lyz lzt
mqw <zw lqz lzw
<yw lty lyq lqt
<xw lwx lxq

```

But I don't see how to shrink it further than that.

And it still uses 6 `<` instructions. Is it conceivably possible to use only 5? Here's a 20-instruction `sort4` (based on this sorting network) that uses only 5 comparisons but is *not stable*, so it doesn't fulfill the challenge:

```
<wy gtw gwy gyt
<xz gtx gxz gzt
<wx gtw gwx gxt
<yz gty gyz gzt
<xy gtx gxy gyt

```

I'm also (finally) realizing that I should have given not only `cmovl` and `cmovg` but also `cmovle` and `cmovge` as primitives; I wonder if that would have helped at all.
> 1 votes

# Answer
## 32 instructions

Here's yet another approach: mergesort. This successfully minimizes the number of `<` operations to 5, but we pay for it with a lot more cmovs. We start by sorting the sublists {*w*, *x*} and {*y*, *z*}; then we merge those two lists. But "merge the two lists" is harder than it sounds. I wrote out the complete game tree; e.g. "First compare *w**y*. If true, the next step will be to compare *x**y*; otherwise, the next step will be to compare *w**z*" and so on. Then rewrite as "If *w**y*, set *i,j**x,y*; otherwise, set *i,j**w,z*. The next step is to compare *i**j*" and so on. That gives an unoptimized program like this:

```
<wx gtw gwx gxt
<yz gty gyz gzt
maw mbx mcy mdz
<ac
  mwa mib mjc m1c m2d m3c m4d m5b m6d m7d m8b
  gwc gia gjd g1b g2d g3d g4b g5a g6b g7a g8b
<ij
  mxi
  gxj g15 g26 g37 g48
<bd
  my1 mz2
  gy3 gz4

```

My best-optimized version takes 32 instructions:

```
<wx gtw gwx gxt
<yz gty gyz gzt
m3y m4z m5x m6z m7z m8x
<wy g48 g5w g6x g7w gwy gx5 gy8 g3z
<x3 gx3 gy5 gz6 g37 g48
<8z gy3 gz4

```
> 0 votes

---
Tags: sorting, atomic-code-golf
---


title: Last odd digit of power of 2

text:
# Question
Title: Last odd digit of power of 2
## Task

Given \\$n\\$, output position of the last odd digit in the decimal representation of \\$2^n\\$ (counting from the end).

## Rules

* There are no odd digits for \\$n=1,2,3,6,11\\$ \\$(2, 4, 8, 64, 2048)\\$ \- you may output anything that is not a positive integer for them (no need to be consistent).
* You choose whether to handle \\$n=0\\$.
* Standard I/O rules.
* This is .

## Test-cases

```
    n answer   (2^n)
    1     NA       2
    2     NA       4
    3     NA       8
    4      2      16
    5      2      32
    6     NA      64
    7      3     128
    8      2     256
    9      2     512
   10      4    1024
   11     NA    2048
   12      2    4096
   13      2    8192
   14      3   16384
   15      3   32768
   16      2   65536
   17      2  131072
   18      3  262144
   19      6  524288
   20      2 1048576

```

*Inspired by this Mathematics SE post and comments on OEIS A068994.*

# Answer
# JavaScript (ES7), 35 bytes

Returns `NaN` if there's no odd digit. Supports \\$n=0\\$.

```
n=>(g=k=>k?k&1||1+g(k/10):+g)(2**n)

```

Try it online!

### Commented

```
n => (        // n = input
  g = k =>    // g = recursive function looking for an odd digit in k
  k ?         // if k is not zero:
    k & 1 ||  //   stop and return 1 if the least significant bit is set
    1 +       //   otherwise, increment the final result
    g(k / 10) //   and do a recursive call with k / 10
              //   note that we rely on arithmetic underflow to stop the
              //   recursion if the LSB is never set
  :           // else:
    +g        //   no odd digit found: return NaN, which will propagate
              //   all the way to the initial call
)(2 ** n)     // initial call to g with k = 2 ** n

```

---

# JavaScript (ES7), 30 bytes

A simpler version that throws an error if there's no odd digit.

```
n=>(g=k=>k&1||1+g(k/10))(2**n)

```

Try it online!
> 8 votes

# Answer
# Excel, 50 bytes

```
=XMATCH(1,MOD(MID(2^A1,1+LEN(2^A1)-ROW(A:A),1),2))

```

Input in cell `A1`. Outputs an `#N/A` error if no odd digit exists.

*Edit: JvdV's wonderfully creative use of passing an array to `TEXTBEFORE` means that we can employ alternatives such as:*

```
=1+LEN(TEXTAFTER(2^A1,{1,3,5,7,9},-1))

```

*for just 38 bytes.*
> 8 votes

# Answer
# Ruby, 31 bytes

```
->n{(2**n).digits.index &:odd?}

```

0-indexed; no result returns `nil`.

I've been programming Ruby for about a year, and really enjoying it. As this example shows, it's possible to be concise and human readable.

`->n{ ... }` is the syntax for creating a lambda. It's not super elegant, but most of the time you're writing methods and not lambdas in Ruby anyways.

`.digits` already returns an array of digits starting with the least significant.

`.index` will search for an item if given an item, but it can also take a tester function, as it does here.

`.odd?` returns whether a number is odd. Prefacing a symbol with `&` creates a function that calls the method associated with that symbol. So `&:odd?` is equivalent to `->(number) { number.odd? }`.
> 8 votes

# Answer
# Python 2, 41 bytes

```
f=lambda n,c=1:2**n/c%2or-~f(n,c%2**n*10)

```

Try it online!

Function that terminates with `ZeroDivisionError` for no output. This happens when the power-of-10 `c` that we're using as a divisor is a multiple of `2**n`, which causes `c%2**n` to reset to 0. This first happens for `c=10**n`, which is bigger than `2**n` so we're already out of digits.

A probably-cheating version instead terminates with `RuntimeError` for exceeding the maximum recursion depth, though usually we pretend this doesn't exist since it would also trigger for very large inputs that should produce an output.

**36 bytes**

```
f=lambda n,c=1:2**n/c%2or-~f(n,c*10)

```

Try it online!
> 7 votes

# Answer
# Julia 1.0, 32 bytes

```
!x=prod(findmax(digits(2^x).%2))

```

Try it online!

1-indexed, works for `0`, and returns `0` for no odd digit
> 7 votes

# Answer
# Haskell, 46 bytes

```
(succ<$>).findIndex(odd.ord).reverse.show.(2^)

```

Try it online!
> 6 votes

# Answer
# Vyxal `gA`, ~~7~~ 5 bytes

```
Ef∷ṘT

```

Try it Online!

`-2` thanks to @lyxal!
> 5 votes

# Answer
# 05AB1E, ~~8~~ 5 bytes

```
oRÅΔÉ

```

0-indexed. Outputs `-1` if there are no odd digits. Also works for \\$n=0\\$.

Try it online or verify the first 26 test cases.

**Original 8 bytes approach:**

```
oSÉRƶ0Kß

```

1-indexed. Outputs an empty string if there are no odd digits. Also works for \\$n=0\\$.

Try it online or verify the first 26 test cases.

**Explanation:**

```
o         # Push 2 to the power of the (implicit) input-integer
 R        # Reverse it
  ÅΔ      # Find the first 0-based index that's truthy for, or -1 if none are:
    É     #  Is the digit odd?
          # (after which the result is output implicitly)

```

```
o         # Push 2 to the power of the (implicit) input-integer
 S        # Convert it to a list of digits
  É       # Check for each digit whether it's odd (1 if odd; 0 if even)
   R      # Reverse this list
    ƶ     # Multiply each value by its 1-based index
     0K   # Remove all 0s
       ß  # Pop and keep the minimum, or an empty string if the list was empty
          # (which is output implicitly as result)

```
> 5 votes

# Answer
# Python 2, ~~46~~ ~~45~~ 53 bytes

*-1 byte thanks to @The Thonnu*
*+8 bytes so it always terminates (added `%(i-2*x)`)*

```
i=2**input()
x=0
while~i/10**x%2%(i-2*x):x+=1
print x

```

Try it online!

Zero indexed, gives a `ZeroDivisionError` for \\$n=1,2,3,6,11\\$.
> 5 votes

# Answer
# Python 2, 53 bytes

```
lambda n:`[int(c)%2for c in`2**n`[::-1]]`.find('1')/3

```

An unnamed function that accepts a non-negative integer, \\$n\\$, and returns the 0-indexed position of the last odd digit of \\$2^n\\$, or \\$-1\\$ if all the digits are even.

**Try it online!**

Note: this actually gets scuppered at \\$n=63\\$ when long ints come into play and the representation of `2**n` acquires a trailing `L`. However, this is about where floating point errors would creep in with division-based methods anyway (this errors while they may start giving incorrect results). This can be dealt with by inserting `if'L'>c` between the `]]` for \\$60\\$.
> 5 votes

# Answer
# Arturo, 40 bytes

```
$=>[index reverse map digits^2&=>[&%2]1]

```

Try it!

0-indexed; no result returns `null`.

```
$=>[            ; a function where input is assigned to &
    ^2&         ; two raised to the input power
    digits      ; get its digits as a list
    map         ; map over the digits...
    =>[&%2]     ; ...modulo two
    reverse     ; reverse
    index ... 1 ; get the index of the leftmost 1
]               ; end function

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~49~~ 47 bytes

```
#&@@Reverse@IntegerDigits[2^#]~Position~_?OddQ&

```

Try it online!
`-2` thanks to @att
> 4 votes

# Answer
# PARI/GP, 36 bytes

```
n->valuation(x*Pol(digits(2^n)%2),x)

```

Attempt This Online!
> 4 votes

# Answer
# Thunno 2 `M`, 5 bytes

```
OdɗrV

```

Attempt This Online! or verify the first 20 test cases

0-indexed. Outputs `[]` if there is no odd digit. Works for \\$n=0\\$.

#### Explanation

```
OdɗrV  # Implicit input
O      # Push 2 ** input
 d     # Convert to digits
  ɗ    # Each mod 2
   r   # Reverse the list
    V  # Truthy indices
       # Take the minimum
       # Implicit output

```
> 4 votes

# Answer
# Bash, 42 bytes

```
i=$[2**n] i=${i#${i%[13579]*}}; echo ${#i}

```

Try it online!
> 4 votes

# Answer
# , 30 bytes

```
\(n)match(1,2^n%/%10^(0:n)%%2)

```

Attempt This Online!
> 3 votes

# Answer
# Scala, 53 bytes

Thanks for the comment to save so many bytes.

Try it online!

1-indexed. "return 0" means missing odd numbers.

```
BigInt(2).pow(_).toString.reverse.indexWhere(_%2>0)+1

```
> 3 votes

# Answer
# MATL, 8 bytes

```
WVooPfX<

```

Output is empty if no solution.

Try it online! Or verify all test cases.

### How it works

```
W    % Implicit input. 2 raised to that
V    % Convert to char vector
o    % Convert each char to code point
o    % Modulo 2
P    % Reverse
f    % Find: gives 1-based indices of non-zeros
X<   % Minimum. Implicit display

```
> 3 votes

# Answer
# Nibbles, 7 bytes (14 nibbles)

```
/`?\`@~^2$%$~

```

Returns `0` if there are no odd digits.

```
/`?\`@~^2$%$~   # full program
             $  # with implicit arg added;
 `?             # find the indices of elements that are truthy by
          %$~   # modulo 2 (default)
                # of
   \            # reverse of
    `@~         # digits in base 10 (default) of
       ^2$      # 2^input
/               # finally fold over this list from right, returning
                # left element each time
                # (so returns first element)

```
> 3 votes

# Answer
# Python 2, 58 bytes

```
lambda n:"".join(`int(i)%2`for i in`2**n`[::-1]).find("1")

```

Attempt This Online!

# Python 3, 65 bytes

```
lambda n:"".join(str(int(i)%2)for i in str(2**n)[::-1]).find("1")

```

Attempt This Online!
> 3 votes

# Answer
# Brachylog, 13 bytes

```
;2^₍↔i%₂ʰℕ₁ʰt

```

Try it online!

### Explanation

```
;2^₍             2^Input
    ↔            Reverse the number
     i           Take a [Digit, Index] of that number
      %₂ʰ        [Digit mod 2, Index]
         ℕ₁ʰ     Digit mod 2 must be in [1,+inf)
            t    Output = Index

```

would mess up indexing in case we reverse a number that ends with 0, but powers of 2 cannot have trailing 0.
> 3 votes

# Answer
# Python 3.8 (pre-release), 46 (40) bytes

40 bytes if input is allowed to be \\$n = 2^t\\$ instead of \\$t\\$ (switched notation). After solving, I saw xnors answer which I think is similar but deals with the power of 2.

```
f=lambda n,j=1:j if n%2else f(n//10,j+1)

```

Try it online!

**26** from xnor by accumulating using 1+f instead of j.

```
f=lambda n:n%2or-~f(n//10)

```

Using this in a \\$2^\cdot\\$ wrapper gives:

**43** 58:

```
lambda t:f(2**t)
f=lambda n:n%2or-~f(n//10)

```

# Python 3.8 (pre-release), 46 bytes

```
f=lambda n,j=0:j if 2**n//10**j%2else f(n,j+1)

```

Try it online!

37 from xnor by accumulating using 1+f instead of j. (Identical except for `n//j` since python 3)

```
f=lambda n,j=1:2**n//j%2or-~f(n,j*10)

```
> 3 votes

# Answer
# Piet \+ ascii-piet, 154 bytes (11×14=154 codels)

```
tldfm?liafqaqQ      ?   i  I rrrjje   e  A ?        e  R biqaasccmu  _             Saeeumcccccc?sVi    qq      Vt    qq sss  Nd    qq  a   Clliqqqq??qfaks

```

Infinite loop for `n = 0, 1, 2, 3, 6, 11, ...` (No odd digits in `n^2`). Outputs correctly for anything with an odd digit. If you want to see how it works, make sure to add input `n` before executing.

Try Piet online!
> 3 votes

# Answer
# Husk, 8 bytes

```
V%2↔d`^2

```

Try it online!

```
V           # Index of first element that is truthy when
 %2         # modulo 2
   ↔        # of the reverse of
    d       # the decimal digits of
     `^2    # 2^input

```
> 2 votes

# Answer
# Japt `-g`, 9 bytes

0-indexed, returns `undefined` if there's no odd digits

```
õ!²Ìì Ôðu

```

Try it

```
õ!²Ìì Ôðu     :Implicit input of integer U
õ             :Range [1,U]
 !²           :Raise 2 to the power of each
   Ì          :Last element
    ì         :Digit array
      Ô       :Reverse
       ð      :0-based indices of elements that truthy (1)
        u     :  Mod 2
              :Implicit output of first element

```
> 2 votes

# Answer
# C++ (gcc), 56 bytes

```
[](int&n){int p=1;for(n=1<<n;n%2-!!n;n/=10)++p;n=n?p:0;}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 12 bytes

```
Ｉ⌕⮌﹪↨Ｘ²Ｎχ²¦¹

```

Try it online! Link is to verbose version of code. 0-indexed. Outputs `-1` if no odd digit exists. Explanation:

```
      ²         Literal integer `2`
     Ｘ          Raised to power
       Ｎ        Input integer
    ↨           Converted to base
        χ       Predefined variable `10`
   ﹪            Vectorised modulo
         ²      Literal integer `2`
  ⮌             Reversed
 ⌕              Find index of
           ¹    Literal integer `1`
                Implicitly print

```

Actually outputting the last odd digit also takes 12 bytes:

```
ＦＩＸ²Ｎ¿﹪Ｉι²Ｐι

```

Try it online! Link is to verbose version of code. Outputs nothing if no odd digit exists. Explanation:

```
ＦＩＸ²Ｎ

```

Loop over the digits.

```
¿﹪Ｉι²

```

If the digit is odd, then...

```
Ｐι

```

... overprint any previous result.
> 2 votes

# Answer
# Retina, 39 bytes

```
~`.+
.+¶$$.($&*$(2$*)_
-1L$`[13579]
$.'

```

Try it online! Link includes test cases. 0-indexed. Outputs nothing if no odd digit exists. Explanation:

```
.+
.+¶$$.($&*$(2$*)_

```

Replace the input with code to calculate that power of `2`. (I could save two bytes by removing the `)_` at the end but this actually prevents a crash in Retina which I feel is not an ideal way to handle zero input.)

```
~`

```

Execute the code to generate the power of `2`.

```
-1L$`[13579]

```

Match the last odd digit.

```
$.'

```

Output the number of digits after it.
> 2 votes

# Answer
# Desmos, 50 bytes

```
I=[0...nlog2]
f(n)=I[mod(floor(2^n/10^I),2)=1].min

```

Counting starts from 0 instead of 1, which is allowed as per the OP. Outputs `undefined` for all-even digits.

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# JavaScript, 61 bytes

Nearly double the length of the other JS answer (and a slightly more naive implementation), but spent a bit of time on it, so might as well post it.

Returns `-0` when there is no odd digit.

```
n=>-(~(l=(z=[...2**n+'']).findLastIndex(i=>i%2))&&l-z.length)

```

Attempt This Online!
> 2 votes

# Answer
# , 26 bytes

```
2{.^:$@I.@:|2x,.@|.&.":@^]

```

0-indexed. Returns an empty array for no odd digit.

Attempt This Online!

```
2{.^:$@I.@:|2x,.@|.&.":@^]
            2x          ^]  NB. 2^input using extended precision literal
                       @    NB. then
              ,.@|.&.":     NB. stringify→reverse then columnize→convert to int
2          |                NB. mod 2 the resulting digit list
         @:                 NB. then
       I.                   NB. find truthy indices
      @                     NB. then
 {.^:$                      NB. get first item, {., if, ^:, the rank, $, is not 0.

```
> 2 votes

# Answer
# BQN, 22 bytes

```
1⊸+|1+·⊐⟜1∘⌊2|2⊸⋆÷10⋆↕

```

Try it at BQN REPL

First find the 0-based index of the first odd digit of the power-of-2 of input  (or return  if all digits are even):

```
⊐⟜1∘⌊2|2⊸⋆÷10⋆↕
        2⊸⋆       # 2 to the power of input
           ÷      # divided by
            10    # 10
              ⋆   # to the power of
               ↕  # range from 0..input;
       |          # modulo
      2           # 2;
     ⌊            # floor;
    ∘             # applied to
⊐⟜1               # find first instance of 1

```

Then fix the cases with all-even digits: change to 1-based indices and output this modulo `+1` (so all-even-digit inputs become zero):

```
1⊸+|1+·
      ·           # last result
    1+            # add 1;
   |              # modulo;
1⊸+               # input plus 1

```
> 2 votes

# Answer
# Swift 5.9, ~~70~~ 68 bytes

```
var o={(n:Int)in String(2<<n).reversed().index{Int("\($0)")!%2==1}!}

```

0-indexed, throws a force-unwrap error when there aren't any odd characters.

Throws a deprecation warning when compiling on modern Swift versions; ignore it.
> 2 votes

# Answer
# Racket – 182 bytes

```
(define(f n)(let l([L(reverse(map(λ(c)(-(char->integer c)48))(string->list(number->string(expt 2 n)))))][I 0])(cond[(odd?(list-ref L I))I][(>(-(length L)1)I)(l L(+ I 1))][#t 'na])))

```

Try it online!

---

## Explanation

We first obtain the list of digits in reversed order of the number \\$ 2^n \\$ and start the index at 0 since Racket uses 0-based indexing. When we convert the number from a string to a list, the digits are represented in ASCII characters. So to extract the digits numeric value we need to subtract 48 from the character's ASCII value (48 in ASCII is the character `0`).

```
(define (last-odd n)
  (let loop ([lst (reverse (map (lambda (char) (- (char->integer char) 48))
                                (string->list (number->string (expt 2 n)))))]
             [index 0])
    ...))

```

Once we have the list of reversed digits, we can begin looping. We create a conditional statement that checks if the current digit is odd. If it is, we return the index. If it isn't odd, we move on to the next check which checks whether we can still loop through the list. If we can, great, we then loop. If all fails, we return `'na`.

```
(define (last-odd n)
  (let loop ([lst (reverse (map (lambda (char) (- (char->integer char) 48))
                                (string->list (number->string (expt 2 n)))))]
             [index 0])
    (cond [(odd? (list-ref lst index)) index]
          [(> (sub1 (length lst)) index) (loop lst (add1 index))]
          [#t 'na])))

```

## Conclusion

I'd like to end this off with an interesting experiment. I'd like to see how this function looks like on a plot. To do this, we can import Racket's `plot` library:

```
(require plot)

```

Now to customize our plot, we can use `parameterize` to set configurations.

```
(require plot)

(parameterize ([plot-width 600]
               [plot-height 480]
               [plot-title "Plot that shows the positions of the last odd digit in 2^n (0 been the last digit)."]
               [plot-x-label "n"]
               [plot-y-label "Last odd digit."]
               [plot-new-window? #t])
  ...)

```

This will open a new window, set its title, set the label of the `x` and `y` axes and set the width and height of the plot. Cool! Now how do we draw on the plot? Simple!

Racket's plot package has a function called plot that plots what ever renderer is in its argument. Since we are using a line graph, we use a line renderer called `lines`.

```
  (plot (lines ...))

```

This renderer receives a sequence of vector points in the form of `#(x y)`. We can programmatically define this sequence using a `for/fold` loop.

```
  (plot (lines (for/fold ([lst empty]) ([index (in-range 0 200)])
                 (let ([result (f index)])
                   (cons (vector index (if (equal? 'na result) 0 result))
                         lst)))))

```

The first argument of the loop is an empty list called `lst` that will be filled after each iteration. The `index` argument is an iterator that is constructed before the iteration begins. If `index` reaches 199, the loop stops and `lst` is returned.

`cons` prepends a value to an existing list. In our case we create a new vector in the form of `#(x y)` where `x` is the current `index` value and `y` is the result of `(f index)`. We then prepend this new vector to `lst` and replace the old `lst` with the new list by returning the constructed list.

Putting this all together:

```
#lang racket

; -- Paste in the golfed code -- ;

(require plot)

(parameterize ([plot-width 600]
               [plot-height 480]
               [plot-title "Plot that shows the positions of the last odd digit in 2^n (0 been the last digit)."]
               [plot-x-label "n"]
               [plot-y-label "Last odd digit."]
               [plot-new-window? #t])
  (plot (lines (for/fold ([lst empty]) ([index (in-range 0 200)])
                 (let ([result (f index)])
                   (cons (vector index (if (equal? 'na result) 0 result))
                         lst))))))

```

Which renders the following:

Pretty interesting! Have an amazing weekend!
> 2 votes

# Answer
# x86, 20 bytes

Assumes input is in ecx and that edx is cleared.

```
B3 0A B0 01 D3 E0 B1 01 F7 FB 89 C2 FF C1 83 E2 01 74 F5 C3

```

```
        mov $10, %bl;     # b = divisor
        mov $1, %al;      # a = 1
        shll %cl, %eax;   # a = 1<<n = 2**n
        mov $1, %cl;      # c = 1, first digit is always even

    loop:
        idiv %ebx;        # a / 10
        movl %eax, %edx;  # a->d for comparison / clearing
        incl %ecx;        # c += 1
        andl $1, %edx;    # a % 2, clears edx if 0, otherwise loop is over
        jz loop;          # if a%2 == 0, loop again

```

Try it online!
> 2 votes

# Answer
# Uiua, 15 bytes

```
⬚∞⊢⊚⇌◿2-@0°⋕ⁿ:2

```

Try it!

0-indexed; returns  for no answer.

```
⬚∞⊢⊚⇌◿2-@0°⋕ⁿ:2
            ⁿ:2  # 2 to the input power
          °⋕     # unparse
       -@0       # convert to digits
     ◿2          # modulo 2
    ⇌            # reverse
   ⊚             # indices of 1s
⬚∞⊢              # first one, or infinity if none exist

```
> 2 votes

# Answer
# Python 2, 64 bytes

```
x=0
for y in`2**input()`[::-1]:
 x+=1
 if int(y)%2:print x;break

```

Try it online!
> 1 votes

# Answer
# Raku, 31 bytes

```
{(2**$_ .flip~~/<[13579]>/).to}

```

Try it online!
> 1 votes

# Answer
# Pip, 8 bytes

```
R%*Ea@?1

```

Outputs 0-indexed: e.g., the output for 2^12 (40**9**6) is 1. Outputs nothing if there is no odd digit.

Attempt This Online!

### Explanation

```
R%*Ea@?1
    a    ; Command-line argument
   E     ; 2 to that power
 %*      ; Take each digit mod 2
R        ; Reverse
     @?1 ; Find index of first occurrence of 1

```
> 1 votes

---
Tags: code-golf, math, number, sequence
---


title: Let the trigonometry begin!

text:
# Question
Title: Let the trigonometry begin!
### **Introduction:**

The sine of \\$x\\$ is given by the formula:

$$\sin(x) = x - \frac {x^3}{3!} + \frac {x^5}{5!} - \frac {x^7}{7!} + \frac {x^9}{9!} - \frac {x^{11}}{11!} + \cdots$$

The cosine of \\$x\\$ is given by the formula:

$$\cos(x) = 1 - \frac {x^2}{2!} + \frac {x^4}{4!} - \frac {x^6}{6!} + \frac {x^8}{8!} - \frac {x^{10}}{10!} + \cdots$$

### **Task:**

Given the value of \\$x\\$ and \\$n\\$, write a program (no functions, etc.) to output the value of \\$\sin(x)\\$ and \\$\cos(x)\\$ correct up to \\$n\\$ terms of the formula above. Assume that \\$x\\$ is in radians.

### **Input:**

```
x n

```

A decimal number \\$x\\$ (with up to 3 decimal places) and an integer \\$n\\$. Input must be on stdin or a prompt dialog box (iff your language doesn't support stdin)

### **Output:**

```
[sin(x)]
[cos(x)]

```

The value of both \\$\sin(x)\\$ and \\$\cos(x)\\$ should be rounded to 6 decimal places. If \\$\sin(x)\\$ is \\$0.5588558855\\$ (10 decimal digits), it should be rounded to \\$0.558856\\$ (6 decimal digits). The rounding must take place to the nearest, as described in the fifth column, "Round to nearest", of the the table in this Wiki article.

### **Constraints:**

```
1 <= x <= 20
1 <= n <= 20

```

### **Samples:**

```
----
5 3

10.208333
14.541667
----
8.555 13

0.765431
-0.641092
----
9.26 10

-3.154677
-8.404354
----
6.54 12

0.253986
0.967147
----
5 1

5.000000
1.000000
----
20 20

-5364.411846
-10898.499385
----

```

### **Notes:**

1. Standard loopholes are prohibited.
2. Built-in math functions and operators of trigonometry (sin, cos, tan, etc.), factorial, and exponentiation cannot be used. You are free to use a built-in rounding function for estimating the result of computing \\$\sin(x)\\$ and \\$\cos(x)\\$ to the 6-th decimal digit.
3. No need to handle wrong inputs.
4. Only ASCII characters can be used in the program, not the Chinese Unicode ones that allow code compression.
5. Your program must terminate, and display the output, within 3 seconds of input.
6. Your answer must accompany the ungolfed code, along with the explanation of the code (compulsory if the code is not immediately obvious to programmers-not-familiar-with-your-language, especially GolfScript, J, etc.).
7. Please include a link to an online compiler where your program can be tested.

### **Scoring:**

The answer with lowest code length in characters, including white space, tabs, etc. wins! Winner would be declared on 21 May 2014.

**EDIT**: 21/05/14 **Winner is aditsu using CJam language. Runner up follows jpjacobs with J language, and second runner up is primo with Perl language**. Congrats all!

# Answer
> 6 votes
# CJam - 42

```
rd:X;1_ri2*,1>{_2%2*(*/X*_}/;]2/z{:+6mO}/p

```

Try it online at http://cjam.aditsu.net

Explanation:

`r` reads a token from the input
`d` converts to double
`:X` assigns to the variable X
`;` pops the value from the stack
`1` puts 1 on the stack (the first term)
`_` duplicates the 1
`r` reads the next token (the n)
`i` converts to integer
`2*,1>{...}/` is a kind of loop from 1 to 2\*n - 1:
\- `2*` multiplies by 2
\- `,` makes an array from 0 to (last value)-1
\- `1>` removes the first item of the array (0)
\- `{...}/` executes the block for each item in the array
`_` duplicates the "loop variable" (let's call it k)
`2%2*(` converts from even/odd to -1/1:
\- `2%` is modulo 2 (-\> 0/1)
\- `2*` multiplies by 2 (-\> 0/2)
\- `(` decrements (-\> -1/1)
`*` multiplies, thus changing the sign every second time
`/` divides the term on the stack by k or -k; this is the "/k!" part of the calculation together with the sign change
`X*` multiplies by X; this is the "X^k" part of the calculation; we obtained the next term in the series
`_` duplicates the term to be used for calculating the following term in the next iteration
`;` (after the loop) pops the last duplicated term
`]` collects the terms on the stack in an array
At this point we have an array \[1 X -X^2/2! -X^3/3! X^4/4! X^5/5! ...\] containing exactly all the terms we need for cos(x) and sin(x), interleaved
`2/` splits this array into pairs
`z` transposes the matrix, resulting in the array with the terms for cos(x) and the array with the terms for sin(x), as "matrix rows"
`{...}/` again executes the block for each array item (matrix row):
\- `:+` adds the elements of the matrix row together
\- `6mO` rounds to 6 decimals
At this point we have the desired cos(x) and sin(x) on the stack
`p` prints the representation of the last item on the stack (sin(x)) followed by a newline
At the end of the program, the remaining contents of the stack (cos(x)) are printed automatically.

# Answer
> 19 votes
## Perl - 72 bytes

```
$~=<>=~$"+$'*2;$_=1-$_*$`/$~--/$~*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;

```

Or, counting command line options as 1 byte each, in **70 bytes**:

```
#!perl -n
$-=/ /+$'*2;$_=1-$_*$`/$---/$-*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;

```

Or, if you'll allow me Perl 5.8, in **63 bytes**:

```
#!perl -p
$.+=$'<</ /;$_=1-$_*$`/$.--/$.*$`for($_=$#='%f
',$\)x$';$_*=$`

```

but why would you.

***Edit**: Compliance with the new rules. `%f` rounds to 6 places by default, how convenient!*

---

**Algorithm**

Examining the Taylor series for *sin(x)*:

it can be seen that each term evenly divides every successive term. Because of this, it can be transformed rather effortlessly into a nested expression:

*cos(x)* transforms similarly, without the leading *x*, and denominator terms one smaller.

Additionally, this nested expression can be reformulated as a reverse recursive expression:

with *s = 0* and *sin(x) = x·s1*, which is ultimately what is used.

---

**Ungolfed**

```
<> =~ m/ /;          # read one line from stdin, match a space
                     # prematch ($`) is now x, postmatch ($') is now n
($x, $n) = ($`, $'); # reassign, for clarity
$i = 2*$n + 1;       # counting variable (denominators)

for (($s, $c)x$n) {  # iterate over $s and $c, n times each
  # compute the next term of the recursive expression
  # note: inside this loop $_ is not the _value_
  # of $s and $c alternately, it _is_ $s and $c

  $_ = 1 - $_ * $x**2 / $i-- / $i;
}

# formated output
printf("%f\n%f", $x*$s, $c);

```

---

**Sample Usage**

```
$ echo 5 3 | perl sin-cos.pl
10.208333
14.541667

$ echo 8.555 13 | perl sin-cos.pl
0.765431
-0.641092

$ echo 9.26 10 | perl sin-cos.pl
-3.154677
-8.404354

$ echo 6.54 12 | perl sin-cos.pl
0.253986
0.967147

$ echo 5 1 | perl sin-cos.pl
5.000000
1.000000

$ echo 20 20 | perl sin-cos.pl
-5364.411846
-10898.499385

```

If you want to test this online, I recommend using compileonline.com. Copy-Paste the code into `main.pl`, and the input into the `STDIN` box, then `Execute Script`.

# Answer
> 9 votes
# Python 3 (102) / Python 2 (104)

**Python 3 (102)**

```
x,n=map(float,input().split())
k=2*n
t=1
while k>1:k-=1;t=1+t*1j*x/k
print('%.6f\n'*2%(t.imag,t.real))

```

**Python 2.7 (104)**

```
x,n=map(float,raw_input().split())
k=2*n
t=1
while k>1:k-=1;t=1+t*1j*x/k
print'%.6f\n'*2%(t.imag,t.real)

```

Basically the same code. We save two characters from not needing parens for `print` but lose four from needing `raw_input`.

**Sample run**

You can run these here.

```
>>>
20 20
-5364.411846
-10898.499385

```

**Code explanation**

The main idea is to compute `2*n` terms of `e^(ix)`, and then take the imaginary and real part to get the `sin` and `cos` values approximated to `n` terms. We use the truncation of the Taylor series:

```
e^(ix)≈sum_{k=0}^{2n-1} (i*x)^k/k!

```

This is polynomial in i\*x, but rather than compute its value by summing each term, we use a modified Horner's Method to compute the sequence (defined recursively in reverse)

```
t_{2n} = 1
t_k = 1 + t_{k+1}*i*x/k,

```

which gives `t_1` equaling the desired value.

Python string formatting operations are used to get the values to display rounded up to 6 decimal digits.

Edit: Changed to round to 6 digits as per new rules. No other changes were needed.

# Answer
> 8 votes
## J 98 70 69 58

Though this can probably be shortened quite a bit using more fancy functions ... comments are welcome:

```
exit echo 0j6":,.-/(($%&(*/)1+i.@[)"0~i.@,&_2)/".}:stdin''

```

note 2: input ends when receiving EOF (ctrl-D in linux). Edit: join exponentiation and factorial into a nicer, more J-ish whole: `($ %&(*/) >:@i.@[ )`. This boils down to take an array of x replications of y and an array of the numbers from 1 to y. Multiply each and divide the result. This gets rid of the duplicate `*/`.

Thanks to algortihmshark, another 7 characters off.

Eliminated cut for getting rid of the trailing newline.

Longer version, for which knowing about forks is a must.

```
NB. recursive Factorial
f=: */@>:@i.      NB. multiply all from 1 to n
NB. Exponential
e=: */@$          NB. replicate y x times, take the product.
NB. the x t y is the Nth (general) term without sign of the joint series
t=: (e % f@[)"0  NB. pretty straight forward: divide by (x!) on the exponential

NB. Piece the parts together, from right to left:
NB. read from stdin, cut the linefeed off , make the 2 n terms in 2 columns, which
NB. effectively splits out pair and odd terms, put in the minuses, put in rows
NB. instead of columns, echo, exit
exit echo 0j6&": ,. (-/) (i.@(,&_2)@{: t {.) , (". ;. _2) stdin''

```

There is no online J interpreter, but it's open source since a few years; installation is easy with these instructions:

http://www.jsoftware.com/jwiki/System/Installation/J801

On #jsoftware on irc.freenode.org, there is a J bot too.

stdin works only when ran from a file, from the commandline, else replace `stdin ''` with `'a b;'` where a and b are the numbers that would have been passed on the commandline.

# Answer
> 6 votes
# Perl, ~~120~~ ~~108~~ ~~104~~ ~~89~~ 85

```
<>=~/ /;$c=$t=1;for(1..2*$'-1){$t*=$`/$_;$_%2?$s:$c+=$_&2?-$t:$t}printf"%f\n"x2,$s,$c

```

Ungolfed:

```
<> =~ / /;
$cosine = $t = 1;
for (1.. 2*$' - 1){
  $t *= $` / $_;
  ($_%2 ? $sine : $cosine) += $_&2?-$t:$t
}
printf "%.6f\n" x2, $sine, $cosine

```

The first line reads the input and uses regex to find a space; this automatically puts the value before the space in $\` and the value after it in $'.

Now we loop from 1 to `2*n-1`. `$t` is our term, which the loop repeatedly multiplies by `x` and divides by the loop's index (`$_`). The loop starts at 1 rather than 0 because the cosine is initialized to 1, which saved me having to deal with dividing by zero.

After updating `$t`, the trinary operator returns either `$sine` or `$cosine`, depending on whether the index is odd or even, and adds `$t`'s value to it. The magic formula `$_&2?-$t:$t` figures whether to add or subtract this value (basically using a bitwise-and on the index and 2 to generate the repeating sequence of "add, add, subtract, subtract").

You can test-run this code at compileonline.com.

# Answer
> 6 votes
## Fortran: ~~89~~ ~~109~~ ~~125~~ ~~102~~ ~~101~~ 98 bytes

```
complex*16::t=1;read*,x,n;do k=2*n-1,1,-1;t=1+t*(0,1)*x/k;enddo;print'(f0.6)',aimag(t),real(t);end

```

I abuse implicit typing, but unfortunately no such implicit complex type exists, so I had to specify that & the complex `i`. ~~Gfortran cuts output at 8 decimal places naturally, so we're good on that spec.~~ Unfortunately, my original method of output, `print*,t`, did not meet specs so I had to add 16 characters to output the imaginary and real components & hit the required 8 decimal places.

Thanks to Ventero, I managed to save 23 bytes between output and the loop. And another character to get correct answers and formatted output. And 3 more on the `read` statement.

Ungolfed,

```
complex*16::t=1
read*,x,n
do k=2*n-1,1,-1
   t=1+t*(0,1)*x/k
enddo
print'(f0.6)',aimag(t),real(t)
end

```

# Answer
> 4 votes
# C, 120

```
double s,c,r,x;main(i,n){for(scanf("%lf %d",&x,&n),r=1;i<n*2;s+=r,r*=-x/i++)c+=r,r*=x/i++;printf("%.8lf\n%.8lf\n",s,c);}

```

To save a byte, the statements that update the sine value are placed inside the `for()` statement, but are actually executed after the statements following the closing parenthesis that update the cosine value. (I guess I could also save a couple more bytes by removing the final newline character in the program's output.)

The global variables `s`, `c`, `r` and `x` are implicitly initialized to zero, and `i` will have a value of 1 as long as there are no arguments provided on the command line. Unfortunately `printf()` defaults to 6 places of decimals, so the output format is a bit verbose.

### Ungolfed:

Here's the code with a bit of rearrangement to make the order in which things are done a bit clearer:

```
double s,c,r,x;
main(i,n) {
    scanf("%lf %d",&x,&n);
    r=1;
    for(;i<n*2;) {
        c+=r;
        r*=x/i++;
        s+=r;
        r*=-x/i++;
    }
    printf("%.8lf\n%.8lf\n",s,c);
}

```

### Sample output:

```
$ echo 1.23 4 | ./sincos
0.94247129
0.33410995

```

### Try it online:

http://ideone.com/URZWwo

# Answer
> 3 votes
## Python \>=2.7.3, ~~186~~ ~~184~~ ~~211~~ ~~200~~ ~~182~~ 170 characters

Kinda simple as hell. Uses formula from the question parameterized for sine and cosine.

Online interpreter can be found ~~here~~ here

```
x,n=map(eval,raw_input().split())
f=lambda n:n<2and 1or n*f(n-1.)
for i in[1,0]:print"%.6f"%sum((1-j%2*2)*reduce(lambda o,p:o*p,[x]*(i+2*j),1)/f(i+2*j)for j in range(n))

```

**Edit:** Valid version with all the restrictions

**Edit2:** Changed online interpreter to ideone.com because of invalid `round` function output in Python 2.7.1

**Edit3:** Turned out that I used unnecessary inline lambda + changed rounding to string format (stolen from xnor :) )

**Edit4:** Replaced `join` with not functional main `for` loop

# Answer
> 3 votes
# GNU bc, driven by bash, 128 bytes

Far too many bytes spent setting decimal places and to-nearest rounding. Oh well, here it is anyway:

```
bc -l<<<"m=1000000
w=s=$1
c=1
for(p=2;p/2<$2;s+=w){w*=-1*$1/p++
c+=w
w*=$1/p++}
s+=((s>0)-.5)/m
c+=((c>0)-.5)/m
scale=6
s/1
c/1"

```

Output:

```
$ ./trig.sh 5 3
10.208333
14.541667
$ ./trig.sh 8.555 13
.765431
-.641092
$ ./trig.sh 9.26 10
-3.154677
-8.404354
$ ./trig.sh 6.54 12
.253986
.967147
$ ./trig.sh 5 1
5.000000
1.000000
$ ./trig.sh 20 20
-5364.411846
-10898.499385
$

```

---

# Linux command-line tools, 97 unicode characters

*Unicode hack answer removed at OP's request. Look at the edit history if you interested.*

# Answer
> 3 votes
**JavaScript - 114 chars**

```
y=(z=prompt)().split(' ');for(x=l=s=+y[0],c=d=1;--y[1];c+=l*=-x/++d,s+=l*=x/++d);z(s.toFixed(6)+'\n'+c.toFixed(6))

```

Based on james' great answer. Same algorithm, first step avoided with initialization of c=1 and s=x. Using 2 vars instead of an array for output simplifies the loop.

**Ungolfed**

```
y = ( z = prompt)().split(' ');
for (
    x = l = s = +y[0], /* init to value x, note the plus sign to convert from string to number */
    c = d = 1;
    --y[1]; /* No loop variable, just decrement counter */
    c += (l *= -x / ++d), /* Change sign of multiplier on each loop */
    s += (l *= x / ++d)
); /* for body is empty */
z(s.toFixed(6) + '\n' + c.toFixed(6))

```

# Answer
> 2 votes
# JavaScript (ECMAScript 6 Draft) - ~~97~~ 96 Characters

A recursive solution:

```
f=(x,n,m=1,i=0,s=x,c=1)=>i<2*n?f(x,n,m*=-x*x/++i/++i,i,s+m*x/++i,c+m):[s,c].map(x=>x.toFixed(8))

```

Output:

```
f(0.3,1)
["0.29550000", "0.95500000"]

f(0.3,24)
["0.29552021", "0.95533649"]

```

# Answer
> 2 votes
# C,114

Insufficient reputation to comment, but further to Squeamish Offisrage's C answer, 7 byte reduction by using float for double and removing spaces, and combining declaration and init of 'r' gives

```
float s,c,r=1,x;main(i,n){for(scanf("%f%d",&x,&n);i<n*2;s+=r,r*=-x/i++)c+=r,r*=x/i++;printf("%.8f\n%.8f\n",s,c);}

```

try here.

# Answer
> 1 votes
# JavaScript (ES6) - 185 chars

```
i=(h,n)=>n?h*i(h,n-1):1;q=x=>x?x*q(x-1):1;p=(a,j,n)=>{for(c=b=0,e=1;c++<n;j+=2,e=-e)b+=e*i(a,j)/q(j);return b.toFixed(6)}
_=(y=prompt)().split(" ");y(p(_[0],1,_[1])+"\n"+p(_[0],0,_[1]))

```

Uses a function `q` for factorial, `i` for exponentiation, and `p` for performing both `sin` and `cos`. Run at jsbin.com. Uses exactly the formula without any modification.

**EDIT**: Changed `8` decimal places to `6` decimal places. 15/May/14

**Ungolfed Code**:

```
/*Note that `name=args=>function_body` is the same as `function name(args){function_body} */

// factorial
function fact(x) {
    return x > 1 ? x * fact(x - 1) : 1
}

// Exponentiation
function expo(number, power){
    return power > 0 ? number * expo(number, power - 1) : 1;
}

function sin_and_cos(number, starter, terms) {
    for (count = sum = 0, negater = 1;
            count++ < terms;
            starter += 2, negater = -negater)

        sum += (negater * expo(number, starter)) / fact(starter);

    // to 6-decimal places
    return sum.toFixed(6);
}

input = (out = prompt)().split(" ");

out(sin_and_cos(input[0], 1,input[1])
        + "\n" +
        sin_and_cos(input[0], 0, input[1]));

```

# Answer
> 1 votes
# Ruby, 336

Probably the longest one here, but I'm sure it could be made shorter :(

```
def f(n)
n==0 ? 1: 1.upto(n).inject(:*)
end
def p(x,y)
i=1
return 1 if y==0
y.times {i *= x}
i
end
def s(x,n)
a = 0.0
for k in 0...n
a += p(-1,k) * p(x.to_f, 1+2*k)/f(1+2*k)
end
a.round(8)
end
def c(x,n)
a= 0.0
for k in 0...n
a +=p(-1,k) * p(x.to_f, 2*k)/f(2*k)
end
a.round(8)
end
x = gets.chomp
n = gets.chomp.to_i
puts s(x,n), c(x,n)

```

# Answer
> 1 votes
**JavaScript - 133 chars**

```
y=(z=prompt)().split(" "),s=[0,0],l=1;for(i=0;i<y[1]*2;i++){s[i%2]+=i%4>1?-1*l:l;l*=y[0]/(i+1)}z(s[1].toFixed(6));z(s[0].toFixed(6));

```

**Ungolfed**

```
var y = prompt().split(" ");

var out = [0,0]; // out[1] is sin(x), out[0] is cos(x)
var l = 1; // keep track of last term in series
for (var i=0; i < y[1] * 2; i++) {
    out[i % 2] += (i % 4 > 1) ? -1 * l : l;
    l *= y[0] / (i + 1);
}

prompt(out[1].toFixed(6));
prompt(out[0].toFixed(6));

```

# Answer
> 1 votes
# Mathematica, 96 chars

```
{{x,n}}=ImportString[InputString[],"Table"];Column@{Im@#,Re@#}&@Fold[1+I#x/#2&,1,2n-Range[2n-1]]

```

# Answer
> 1 votes
# Ruby - ~~160~~ ~~152~~ 140 Chars

Using recursion and the fact that for this recursive implementation sin(x, 2n + 1) = 1 + cos(x, 2n - 1), being sin(x, n) and cos(x, n) the series defined above for cos x and sin x.

```
p=->x,n{n<1?1:x*p[x,n-1]}
f=->n{n<2?1:n*f[n-1]}
c=->x,n{n<1?1:p[x,n]/f[n]-c[x,n-2]}
x,n=gets.split.map &:to_f
n*=2
puts c[x,n-1]+1,c[x,n-2]

```

Edit: Contributed by commenters (read below).

# Answer
> 1 votes
# APL(NARS), 109 chars

```
r←a F w;d;v;m;p
r←d←1+(2≠↑a)×w-1⋄m←w×w×¯1⋄p←2⊃a⋄v←0 1-2=↑a
→0×⍳0≥p-←1⋄r+←d×←m÷×/v+←2⋄→2

⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕

```

15+42+28+2+22=109

the last line call the function F that is a sin and cos function depend of first input on the left (it is ≠2 is sin input =2 is cos). Some test:

```
      ⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
      5 3
  10.208333
  14.541667
      ⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
      8.555 13
  0.765431
  ¯0.641092
      ⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
      9.26 10
  ¯3.154677
  ¯8.404354

```

OT it would be possible to calculate the *exact* answer using rationals and input rational for example of 1r4 (0.25=1/4)

```
      ⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
      1r4 10
  0.247404
  0.968912
      {⍵○1r4}¨⍳2
  0.2474039593 0.9689124217
      {⍵○0.25}¨⍳2
  0.2474039593 0.9689124217
      1 10 F 1r4
  8264318085745811128158727r33404146443928530321408000
      2 10 F 1r4
  17051609536099989115458551r17598710837038136237752320

```

these last 2 numbers both cut would be the decimals 0.2474039592 and 0.9689124217

---
Tags: code-golf, math, trigonometry, approximation
---