text:
Sum the powers that be
A simple but hopefully not quite trivial challenge:
Write a program or function that adds up the kth powers dividing a number n. More specifically:

Input: two positive integers n and k (or an ordered pair of integers, etc.)
Output: the sum of all of the positive divisors of n that are kth powers of integers

For example, 11! = 39916800 has six divisors that are cubes, namely 1, 8, 27, 64, 216, and 1728. Therefore given inputs 39916800 and 3, the program should return their sum, 2044.
Other test cases:
{40320, 1} -> 159120
{40320, 2} -> 850
{40320, 3} -> 73
{40320, 4} -> 17
{40320, 5} -> 33
{40320, 6} -> 65
{40320, 7} -> 129
{40320, 8} -> 1
{46656, 1} -> 138811
{46656, 2} -> 69700
{46656, 3} -> 55261
{46656, 4} -> 1394
{46656, 5} -> 8052
{46656, 6} -> 47450
{46656, 7} -> 1
{1, [any positive integer]} -> 1

This is code golf, so the shorter your code, the better. I welcome golfed code in all kinds of different languages, even if some other language can get away with fewer bytes than yours.

When I first saw your challenge, I had the weird feeling that it was a Metallica song title.

What? There's no Mathematica built-in for this?

05AB1E, 9 bytes
DLImDŠÖÏO

Try it online!
Explanation
Example input 46656, 3
D          # duplicate first input
           # STACK: 46656, 46656
 L         # range [1 ... first input]
           # STACK: 46656, [1 ... 46656]
  Im       # each to the power of second input
           # STACK: 46656, [1, 8, 27 ...]
    D      # duplicate
           # STACK: 46656, [1, 8, 27 ...], [1, 8, 27 ...]
     Š     # move down 2 spots on the stack
           # STACK: [1, 8, 27 ...], 46656, [1, 8, 27 ...]
      Ö    # a mod b == 0
           # STACK: [1, 8, 27 ...], [1,1,1,1,0 ...]
       Ï   # keep only items from first list which are true in second
           # STACK: [1, 8, 27, 64, 216, 729, 1728, 5832, 46656]
        O  # sum
           # OUTPUT: 55261

Mathematica, 28 bytes
Tr[Divisors@#⋂Range@#^#2]&

Unnamed function taking n and k as inputs in that order.

DivisorSum is frustratingly close to being useful here.

Jelly, 7 6 bytes
-1 byte thanks to Dennis (traverse an implicit range)
A clever efficiency save also by Dennis at 0-byte cost
(Previously ÆDf*€S would filter keep those divisors that are a power of k of any natural number up to n. But note that n can only ever have a divisor of ik if it has a divisor of i anyway!)
ÆDf*¥S

Try it online!
How?
ÆDf*¥S - Main link: n, k
ÆD     - divisors of n  -> divisors = [1, d1, d2, ..., n]
    ¥  - last two links as a dyadic chain
  f    -     filter divisors keeping those that appear in:
   *   -     exponentiate k with base divisors (vectorises)
       - i.e. [v for v in [1, d1, d2, ..., n] if v in [1^k, d1^k, ..., n^k]]
     S - sum

Python 2, 54 52 bytes
lambda x,n:sum(i**n*(x%i**n<1)for i in range(1,-~x))

Thanks @Rod for cutting off 2 bytes.

You can replace x%i**n==0 with x%i**n<1, and move to the other side as i**n*(x%i**n<1)

Haskell, 37 35 34 bytes
n!k=sum[x^k|x<-[1..n],n`mod`x^k<1]

Try it online! Usage:
Prelude> 40320 ! 1
159120

The code is quite inefficient because it always computes 1^k, 2^k, ..., n^k.
Edit: Saved one byte thanks to Zgarb.
Explanation:
n!k=             -- given n and k, the function ! returns
 sum[x^k|        -- the sum of the list of all x^k
   x<-[1..n],    -- where x is drawn from the range 1 to n
   n`mod`x^k<1]  -- and n modulus x^k is less than 1, that is x^k divides n

mod n(x^k) can be n\mod`x^k`.

Ruby, 45 bytes
->n,m{(1..n).reduce{|a,b|n%(c=b**m)<1?a+c:a}}

Would be shorter using "sum" in Ruby 2.4. Time to upgrade?

Time to upgrade.

MATL, 10 bytes
t:i^\~5M*s

Try it online!
How it works
Example with 46656, 6.
t      % Implicitly input n. Duplicate
       % STACK: 46656, 46656
:      % Range
       % STACK: 46656, [1 2 ... 46656]
i      % Input k
       % STACK: 46656, [1 2 ... 46656], 6
^      % Power, element-wise
       % STACK: 46656, [1 64 ... 46656^6]
\      % Modulo
       % STACK: [0 0 0 1600 ...]
~      % Logically negate
       % STACK: [true true true false ...]
5M     % Push second input to function \ again
       % STACK: [true true true false ...], [1^6 2^6 ... 46656^6]
*      % Multiply, element-wise
       % STACK: [1 64 729 0 ...]
s      % Sum of array: 47450
       % Implicitly display

Perl 6, 39 bytes
->\n,\k{sum grep n%%*,({++$**k}...*>n)}

How it works
->\n,\k{                              }  # A lambda taking two arguments.
                        ++$              # Increment an anonymous counter
                           **k           # and raise it to the power k,
                       {      }...       # generate a list by repeatedly doing that,
                                  *>n    # until we reach a value greater than n.
            grep n%%*,(              )   # Filter factors of n from the list.
        sum                              # Return their sum.

Try it

JavaScript (ES7),  56 53  47 bytes
Expects (n)(k).
n=>k=>eval("for(i=t=0;i++<n;)t+=n%i**k?0:i**k")

Try it online!

Python 2, 50 bytes
f=lambda n,k,i=1:n/i and(n%i**k<1)*i**k+f(n,k,i+1)

Try it online! Large inputs may exceed the recursion depth depending on your system and implementation.

this is 49 bytes, and it may be valid since True quacks like 1, but it's a strange default imo

Japt, 10 bytes
Saved lots of bytes thanks to @ETHproductions
òpV f!vU x

Explanation
òpV f!vU x
ò           // Creates a range from 0 to U
 pV         // Raises each item to the power of V (Second input)
    f       // Selects all items Z where
     !vU    //   U is divisible by Z
            //   (fvU would mean Z is divisible by U; ! swaps the arguments)
         x  // Returns the sum of all remaining items

Test it online!

Does vU detect numbers divisible by U, or numbers that divide U?

@GregMartin fvU filters to items that are divisible by U; f!vU filters to items that U is divisible by. ! swaps the arguments.

Cool, so the code looks right, but the explanation might need to be tweaked.

@GregMartin Should be clearer now.

Scala 63 bytes
(n:Int,k:Int)=>1 to n map{Math.pow(_,k).toInt}filter{n%_==0}sum

JavaScript (ES7), 49 46 bytes
n=>g=(k,t=i=0,p=++i**k)=>p>n?t:g(k,t+p*!(n%p))

Since you aren't recursing, why not n=>k=>? +1.

@TuukkaX I came up with something better. (I actually had this earlier with i as a local, which costs 4 extra bytes, and forgot that I could abuse i in the same way that I did with my other formulation.)

APL (Dyalog Classic), 14 bytes
+/*⍨∘⍳(⊣×0=|)⊢

Try it online!
Takes the power as the left argument and the number as the right. Even at 128-bit precision, the last couple of test cases exceed the max int size.
Explanation:
     ⍳            ⍝ The range 1 to right argument
  *⍨∘             ⍝ Each raised to the power of the left argument
      (     )⊢    ⍝ Apply the train to this and the right argument
       ⊣×         ⍝ Multiply each power
         0=|      ⍝ By if the right argument is divisible by it
+/                ⍝ And sum

Pip, 15 bytes
$+Ya%_FN(\,a)Eb

Try It Online!

PHP, 86 bytes
$n=$argv[1];$k=$argv[2];for($i=1;$i<=$n**(1/$k);$i++)if($n%$i**$k<1)$s+=$i**$k;echo$s;

Try it here !
Breakdown :
$n=$argv[1];$k=$argv[2];       # Assign variables from input
for($i=1;$i<=$n**(1/$k);$i++)  # While i is between 1 AND kth root of n
    if($n%$i**$k<1)            #     if i^k is a divisor of n
        $s+=$i**$k;            #         then add to s
echo$s;                        # echo s (duh!)

golfed, but not tested: for(;$x<$n=$argv[1];)$n%($x=++$i**$argv[2])?:$s+=$x;echo$s; 59 bytes; requires PHP 5.6 or later.

CJam, 20 bytes
Probably not optimally golfed, but I don't see any obvious changes to make...
ri:N,:)rif#{N\%!},:+

Try it online!

Jelly, 8 bytes
R*³%$ÐḟS

Try it online!
(Credit not mine.)

Bash + Unix utilities, 44 bytes
bc<<<`seq "-fx=%.f^$2;s+=($1%%x==0)*x;" $1`s

Try it online!
Test runs:
for x in '40320 1' '40320 2' '40320 3' '40320 4' '40320 5' '40320 6' '40320 7' '40320 8' '46656 1' '46656 2' '46656 3' '46656 4' '46656 5' '46656 6' '46656 7' '1 1' '1 2' '1 3' '1 12' ; do echo -n "$x "; ./sumpowerdivisors $x; done

40320 1 159120
40320 2 850
40320 3 73
40320 4 17
40320 5 33
40320 6 65
40320 7 129
40320 8 1
46656 1 138811
46656 2 69700
46656 3 55261
46656 4 1394
46656 5 8052
46656 6 47450
46656 7 1
1 1 1
1 2 1
1 3 1
1 12 1

Python, 56 bytes
lambda n,k:sum(j*(j**k**-1%1==n%j)for j in range(1,n+1))

Try it online!
Fairly straightforward. The only noteworthy thing is that j**k**-1%1 always returns a float in [0,1) while n%j always returns a non-negative integer, so they can only be equal if both are 0.

Batch, 138 bytes
@set s=n
@for /l %%i in (2,1,%2)do @call set s=%%s%%*n
@set/at=n=0
:l
@set/an+=1,p=%s%,t+=p*!(%1%%p)
@if %p% lss %1 goto l
@echo %t%

Since Batch doesn't have a power operator, I'm abusing set/a as a form of eval. Very slow when k=1. 32-bit integer arithmetic limits the supported values of n and k:
           n   k
  (too slow)   1
 <1366041600   2
 <1833767424   3
 <2019963136   4
 <2073071593   5
 <1838265625   6
 <1801088541   7
 <1475789056   8
 <1000000000   9
 <1073741824  10
 <1977326743  11
  <244140625  12
 <1220703125  13
  <268435456  14
 <1073741824  15
   <43046721  16
  <129140163  17
  <387420489  18
 <1162261467  19
    <1048576  20
           ...
 <1073741824  30

R, 35 bytes
function(n,k)sum((a=(1:n)^k)*!n%%a)

Try it online!
3 years later, but 6 bytes shorter than the previous R answer.

Husk, 10 9 8 bytes
ΣnḊ³m^⁰ḣ

Try it online!
-1 byte from Jo King.
-1 more byte from Jo King.
Explanation
ΣnḊ³m^⁰ḣ
       ḣ range 1..n
    m^⁰  each raised to power k
 n       set intersection with
  Ḋ³     divisors of n
Σ        sum the list

Japt -x, 9 bytes
ÆvX=pV)*X

Try it
8 bytes
My first pass. Realised as I was about to post it that it's pretty much identical to Oliver's existing solution.
opV f@vX

Try it
ÆvX=pV)*X     :Implicit input of integers U=n & V=k
Æ             :Map each X in the range [0,U)
 v            :  Is U divisible by
  X=          :    Reassign to X
    pV        :    X raised to the power of V
      )       :  End divisibility check
       *X     :  Multiply by X
              :Implicit output of sum of resulting array

Vyxal, 6 bytes
K:?e↔∑

Try it Online!

R,     28 bytes direct, 43 bytes for function
if n,k in memory:
sum((n%%(1:n)^k==0)*(1:n)^k)

for a function:
r=function(n,k)sum((n%%(1:n)^k==0)*(1:n)^k)


text:
HRNG - Human Random Number Generator
You know it: keyboard or mouse input is just too mainstream to create Random Numbers through human behavior.
Create the most unique (Pseudo)Random Number Generator that create its numbers through human behavior.
Web-API's are not restricted! Anyone should use the code provided, so any special hardware is restricted. (I think we can assume that everyone has a smartphone)
The number should be a 256 bit number.
Example: use the Google Map's API to get current traffic to create the Random Number.
This is a popularity-contest, so most votes wins!

Related, possibly duplicate?

Related but no Duplicate. It restrict to Internet Access and use any item laying around. The Point what here should use: anyone should use the code without special hardware.

Can I use random on the data I gathered or it has to be purely independent of the in built random function of my language?

So, should it be heavily biased toward red hammers?

Aaron red hammers? hashcode55: you can, but it would be not so good for a human based random number generator ;) Qwerp-Derp: what is a reasonable length? End of February?

Mathematica on Mac OS X
Mod[Tr /@ IntegerDigits[
  Floor[2^15 AudioData@SystemDialogInput@"RecordSound"]
, 2], 2]

Opens up a dialog box that lets you record a sound snippet through the computer's microphone, then converts the resulting digital audio data to a list of bits (roughly 50,000 bits per second of audio). Generate random numbers through white noise, singing your favorite tune, exclaiming "Serenity now!", or just yelling at the top of your lungs!

Will give +1 if you send a vid link of you running it and yelling really loud

Python 3
import urllib.request
t=0
with urllib.request.urlopen("http://codegolf.stackexchange.com/questions/109658/hrng-human-random-number-generator#109658") as f:
    m = f.read().decode("utf8")
    for c in m:
        t+=ord(c)
print(t/len(m.split()))

This version takes each characters ordinals to take into account changing values such as votes.
Leaving the below in as it was my first attempt but as noted it is a little stale.
import urllib.request
with urllib.request.urlopen("http://codegolf.stackexchange.com/questions/109658/hrng-human-random-number-generator#109658") as f:
    m = f.read().decode("utf8")
print(len(m)/len(m.split()))

Takes this current page gets it's character count and word count divides and returns the number.
Not sure if it's great but first idea that came to mind.

+1 I really like this answer! Though, it won't update too often haha. A more frequently updating answer could be taking the hash of the page and converting it to numeric form (using modulo and others) because then you get all of the minor changes as well (changes that dont increase character count) such as any user here getting reputation. Any timestamp updating. etc

@AlbertRenshaw - Thank you :D - That change of course would be a much better way for me to do it, I'll have a look at a changing it when I get back on a proper computer (using mobile atm).

Bash
w|sha256sum|tr -d -

Outputs a hex-encoded 256 bit "random" number

w  displays information about the users currently on the machine, and their processes.  The header shows, in this order, the current time, how long the system has been running, how many users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes.

Try It Online !

@FlipTack, yep, just a habit :)

source: Stack Exchange

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

sort: votes


text:
Can't see the forest for the trees
Write a program or function that draws a tree of trees, thus constructing a forest.
The trees are drawn like stacking a pyramid. The first (top) row contains 1 tree, the next row down contains 2 (for a total of 3), the next contains 3 (for a total of 6), and so on. If there aren't enough trees to complete a full row, fill it to the left and leave the spots on the right empty. Additionally, lower-level trees slightly overlap upper-level trees due to their placement.
This is a forest of size 1
  /\
 //\\
///\\\
  ||
  ||

This is a forest of size 2
      /\
     //\\
  /\///\\\
 //\\ ||
///\\\||
  ||
  ||

This is a forest of size 3
      /\
     //\\
  /\///\\\/\
 //\\ || //\\
///\\\||///\\\
  ||      ||
  ||      ||

This is a forest of size 4
          /\
         //\\
      /\///\\\/\
     //\\ || //\\
  /\///\\\||///\\\
 //\\ ||      ||
///\\\||      ||
  ||
  ||

This is a forest of size 5 (note the top of the fifth tree is covering the trunk of the first tree)
          /\
         //\\
      /\///\\\/\
     //\\ || //\\
  /\///\\\/\///\\\
 //\\ || //\\ ||
///\\\||///\\\||
  ||      ||
  ||      ||

(skip a few)
This is a forest of size 8 (extending the pattern)
              /\
             //\\
          /\///\\\/\
         //\\ || //\\
      /\///\\\/\///\\\/\
     //\\ || //\\ || //\\
  /\///\\\/\///\\\||///\\\
 //\\ || //\\ ||      ||
///\\\||///\\\||      ||
  ||      ||
  ||      ||

and so on.
Input
A single positive integer in any convenient format, n > 0.
Output
An ASCII-art representation of the forest, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the trees all line up appropriately.
Rules

Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

I'm not sure what the pattern is regarding the order in which the trees are drawn. That is, given n, what are the positions of the trees?

@LuisMendo As I understand, they are filled in reading order. So, each row is filled in turn, and if there's not enough trees for the whole row, the remainder are placed as far left as possible in that row.

@LuisMendo xnor has it right. If I can re-word that to make it more clear, please ping me in chat.

@xnor Thanks, it's totally clear to me now

@Adm Actually it was written right there in the challenge. Apparently I can't read :-)

Haskell 310 bytes
w i=putStr$unlines$reverse$b i 0 0[][]
b 0 _ _ w r=e w r
b c l 0 w r=b c(l+1)l(e w r)[]
b c l p w r=b(c-1)l(p-1)w(n(++)["  ||    ","  ||    ","///\\\\\\  "," //\\\\   ","  /\\    "]r)
e w r=t++n(n d)(map(\t->"    "++t)w)c where(t,c)=splitAt 2 r
n f(a:c)(b:d)=f a b:n f c d
n _ a[]=a
n _ _ a=a
d d ' '=d
d _ d=d

Call it with w 5, for example.
Here the uncompressed code:
-- TreeTree
-- by Gerhard
-- 12 February 2017

module TreeTree (wood,test) where

type Tree = [String]

-- Test cases
test = do
 wood 0
 wood 1
 wood 2
 wood 3
 wood 4
 wood 5

-- build wood
wood :: Int -> IO ()
wood i = printTree $ buildWood i 0 0 [] []

-- Prints the trees
printTree :: Tree -> IO ()
printTree = putStr . unlines . reverse

-- build wood
buildWood :: Int -> Int -> Int -> Tree -> Tree -> Tree
buildWood 0 _ _ w r = concatTree w r
buildWood c l 0 w r = buildWood c (l+1) l (concatTree w r) []
buildWood c l p w r = buildWood (c-1) l (p-1) w (addTree r)

-- indent definition
space :: String
space = "    "

-- tree definition
tree :: Tree
tree = reverse [
 "  /\\    ",
 " //\\\\   ",
 "///\\\\\\  ",
 "  ||    ",
 "  ||    "]

-- Add a Tree on the left side
addTree :: Tree -> Tree
addTree = match (++) tree

-- add tree row at the bottom of the wood
concatTree :: Tree -> Tree -> Tree
concatTree w r = trunk ++ matched
 where
  wood = grow w
  (trunk, crown) = splitAt 2 r
  matched = matchTree wood crown

-- elnarge forrest on the left side to match next tree line
grow :: Tree -> Tree
grow = map (\t -> space ++ t)

-- match
match :: (a -> a -> a) -> [a] -> [a] -> [a]
match f (a:az) (b:bz) = f a b : match f az bz
match _ a [] = a
match _ _ a  = a

-- match trees
matchTree :: Tree -> Tree -> Tree
matchTree = match matchLine

-- match lines
matchLine :: String -> String -> String
matchLine = match matchChar

-- match chars
matchChar :: Char -> Char -> Char
matchChar c ' ' = c
matchChar _ c   = c

-- End

Welcome to PPCG!

C++ (on Windows), 330 312 308 304 303 bytes
#import<cstdio>
#import<windows.h>
#define P(x,y,s)SetConsoleCursorPosition(GetStdHandle(-11),{X+x,Y+y});puts(s);
int X,Y,R,r,c;t(){P(2,-2,"/\\")P(1,-1,"//\\\\")P(0,0,"///\\\\\\")P(2,1,"||")P(2,2,"||")}f(int n){for(c=R=r=1;c<n;c+=++R);for(;r;r++)for(c=0;++c<r+1;){X=(R-r-2)*4+c*8;Y=r*2;t();r=--n?r:-1;}}

Call with:
int main()
{
    f(8);
}

JavaScript (ES6), 357 297 276 bytes

f=
n=>{a=`  /\\`;d=`///\\\\\\`;b=d+`/\\`;c=` //\\\\ ||`;d+=`||`;e=`
`;r=`repeat`;s=``;for(i=1;n>i;n-=i++)s=(s+a+b[r](i-1)+e+c[r](i)).replace(/^/gm,`    `)+e;return(s+a+b[r](n-1)+d[r](i-=n)+e+c[r](n)+(s=`      ||`[r](i))+e+d[r](n)+s+(s=e+`  ||    `[r](n))+s).replace(/\|.$/gm,``)}
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

Edit: Saved 21 bytes thanks to @KritixiLithos.

For the first repeat, you can change blah.repeat(val) to blah[w="repeat"](val) and then you can change the subsequent occurences of repeat to just [w](val) instead to save bytes

@KritixiLithos I can't quite do that because the first repeat is inside the for loop and won't run for n=1, but I was still able to save 21 bytes.

Javascript 418 377 bytes
Thanks to @Kritixi Lithos for helping golf off 39 bytes
x=>{s='';for(t=0;++t<x;x-=t);q='//\\\\';z="///\\\\\\";h="/\\";t--;for(i=0;i<t;i++){a=4*(t-i)+1;s+=" "[w="repeat"](a+1)+h+(z+h)[w](i)+`
`+" "[w](a)+q+(" || "+q)[w](i)+`
`}c=t-x+1>0?t-x+1:0;return x?s+"  "+(h+z)[w](--x)+h+(c?(z+"||")[w](c-1)+z:'')+`
 `+q+(" || "+q)[w](x)+" ||     "[w](c)+`
`+(z+"||")[w](x)+z+(c?"||"+"      ||"[w](c-1):'')+`
`+("  ||    "[w](x+1)+`
`)[w](2):''}

Try it Online

For the first repeat, you can change blah.repeat(val) to blah[w="repeat"](val) and then you can change the subsequent occurences of repeat to just [w](val) instead to save bytes

C (on Windows), 297 295 294 bytes
#import<windows.h>
#define P(x,y,s)C.X=X+x;C.Y=Y+y;SetConsoleCursorPosition(GetStdHandle(-11),C);puts(s);
COORD C;X,Y,R,r,c;t(){P(2,-2,"/\\")P(1,-1,"//\\\\")P(0,0,"///\\\\\\")P(2,1,"||")P(2,2,"||")}f(n){for(c=R=r=1;c<n;c+=++R);for(;r;r++)for(c=0;++c<r+1;){X=(R-r-2)*4+c*8;Y=r*2;t(r=--n?r:-1);}}

Similar to my C++ answer, but I posted this because it's somewhat shorter in C.

@DLosc It's C. #import is a (deprecated) GCC extension. Fit for golfing, though.

Huh, interesting. Now I see that there's a tip for that. You might mention that in your answer.

@DLosc Perhaps, but I think it's quite widely used in golfing, along with some other GCC (though not limited to GCC) extensions like omitting <stdio.h> and automatically assuming a global variable to be int or a function to return int.

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


text:
Necklace splitting problem
Background
I was inspired by 3Blue1Brown's recent video about the necklace splitting problem (or as he calls it, the stolen necklace problem) and its relationship to the Borsuk-Ulam theorem.
In this problem, two thieves have stolen a valuable necklace consisting of several different types of jewels. There are an even number of each type of jewel and the thieves wish to split each jewel type evenly amongst the two of them. The catch is that they must do so by splitting the necklace into some number of contiguous segments and distribute the segments between the two of them.
Here is an example with four jewel types denoted S, E, D, and R (for sapphire, emerald, diamond, and ruby, respectively). Let's say the necklace is as follows:
[S,S,S,E,S,D,E,R,S,R,E,S,S,S,D,R,E,E,R,E,D,E,R,R,D,E,E,E]

There are 8 sapphires, 10 emeralds, 4 diamonds, and 6 rubies. We can split the necklace as follows:
[[S],[S],[S,E,S,D,E,R,S],[R,E,S,S,S,D,R,E,E,R,E,D,E],[R,R,D,E,E,E]]

Then if we give the first, third, and fifth segments to one thief and the second and fourth segments to the other thief, each will end up with 4 sapphires, 5 emeralds, 2 diamonds, and 3 rubies:
[S],    [S,E,S,D,E,R,S],                            [R,R,D,E,E,E]
    [S],                [R,E,S,S,S,D,R,E,E,R,E,D,E],

Using 0-indexing, these cuts occur at the indices [1,2,9,22].
Goal
It turns out that such a fair division can always be done using at most n cuts, where n is the number of jewel types. Your task is to write a complete program or function which takes a necklace as input and outputs a minimal such division (fewest number of cuts).
Input
Input may be in any convenient format. The necklace should be a sequence of jewels and nothing more; e.g. a list of integers, dictionary with keys representing the jewel types and values being lists of indices. You may optionally include the length of the necklace or the number of distinct jewel types, but you should not take any other input.
You may assume that the input necklace is valid. You do not need to handle the case where there is an odd number of jewels of a given type or the necklace is empty.
Output
Again, output may be in any convenient format; e.g. a list of segments, a list of cut positions, a dictionary with keys representing the two thieves and values being lists of segments, etc. Segments may be represented by their starting index, ending index, list of consecutive indices, list of jewels, their lengths, etc. You may use 0- or 1- indexing. If the ordering is not significant to your format, then your output may be in any order. Here is the above output in several different formats:
list of segments: [[S],[S],[S,E,S,D,E,R,S],[R,E,S,S,S,D,R,E,E,R,E,D,E],[R,R,D,E,E,E]]
list of cuts:     [1,2,9,22]
list of lengths:  [1,1,7,13,6]
dictionary:       {'thief1' : [(R,R,D,E,E,E),(S),(S,E,S,D,E,R,S)], 'thief2' : [(S),(R,E,S,S,S,D,R,E,E,R,E,D,E)]}

Note that order is important in the list of segments (segments alternate between the thieves) and the list of lengths (in order to identify the segments), but not in the list of cuts or the dictionary. Edit: Greg Martin pointed out that these wouldn't be valid outputs since a fair division can be obtained in two cuts
Test cases
[1,2,1,2,1,3,1,3,3,2,2,3] -> [[1,2,1],[2,1,3,1],[3,3,2],[2,3]]
[1,1,1,1,2,2,3,3,3,3,3,3] -> [[1,1],[1,1,2],[2,3,3,3],[3,3,3]]
[1,1,1,1,1,1,1,1,1,1,1,1] -> [[1,1,1,1,1,1],[1,1,1,1,1,1]]
[1,1,1,1,2,3,4,2,3,4,2,2] -> [[1,1],[1,1,2,3,4,2],[3,4,2,2]]

Notes

Standard loopholes are forbidden.
This is code-golf; shortest answer (in bytes) wins.

Is the necklace circular?

@Dennis No, the necklace is linear.

May we represent each segment in the output by its length?

@JanDvorak I will add that as an option.

Note to adjust note #2 as it clashes with that option.

@JanDvorak Noted. I hope I've covered my bases sufficiently now.

I think you did. Still not sure why you don't allow outputting just the segments themselves instead of indices.

@JanDvorak To be honest, I don't know either. I'll remove it.

Can we take the input as letters/tokens indicating the different jewel types, instead of integers?

So, is there anything wrong with just returning a list of the segments themselves?

If the order of segments isn't changed, the pieces alternate between theif A and theif B. As such, including that information in the output is redundant. Can we omit the theif indication if the answer doesn't change the order of the jewels? Do you have some test cases?

@GregMartin Yes, you may take input in any reasonable format.

@JonathanAllan That's fine.

@Luke I added a few.

For your example [S,S,S,E,S,D,E,R,S,R,E,S,S,S,D,R,E,E,R,E,D,E,R,R,D,E,E,E], it seems that the output should be [[S,S,S,E,S,D,E,R],[S,R,E,S,S,S,D,R,E,E,R,E,D,E],[R,R,D,E,E,E]], since that has fewer cuts than [[S],[S],[S,E,S,D,E,R,S],[R,E,S,S,S,D,R,E,E,R,E,D,E],[R,R,D,E,E,E]]. Am I understanding the spec correctly?

@GregMartin Indeed I was just about to ask the same question. The spec says "a minimal such division" which doesnt make sense semantically, because OP just stated it can be done in at most n cuts so n is in a way the maximum. The minimum in this case is 2, not n=4. Given the example, my understanding was the exact opposite of yours,i.e. it is sufficient to do it in n cuts..

I agree the example seems to imply that; however, "minimal such division (fewest number of cuts)" is a quote from the problem statement.

@GregMartin You're correct. The intention with that example wasn't to show a minimal division, but I didn't do a good job explaining that.

Brachylog, 13 bytes
~c.ġ₂z₁Ċcᵐoᵛ∧

Try it online!
Note: the metapredicate ᵛ is newer than this challenge.
Explanation
~c.ġ₂z₁Ċcᵐoᵛ∧  Input is a list, say L = [1,2,2,2,1,2,3,3]
~c.            Output is a partition of the input: [[1,2,2],[2,1,2],[3],[3]]
  .ġ₂          Split the output into chunks of length 2: [[[1,2,2],[2,1,2]],[[3],[3]]]
     z₁        Zip (transpose) the chunks: [[[1,2,2],[3]],[[2,1,2],[3]]]
       Ċ       This is a 2-element list (forbid the trivial partition).
        cᵐ     Concatenate both: [[1,2,2,3],[2,1,2,3]]
          oᵛ   If you sort both lists, they are equal.
            ∧  Don't unify with the output.

The partitions are enumerated in increasing order of the number of blocks, so the result will have as few blocks as possible.

Jelly, 18 bytes
s2ZFṢ$€E¬,L
ŒṖṖÇÞḢ

Try it online!
Not efficient - the example has 28 jewels which wont work without huge resources since this implementation's first step would be to build a list of the 227 possible partitions.
Returns a list of lists - the segments in the order to dish them out between alternate thieves. (Re the TIO output: when a list only has a single item the implicit print does not bother with the brackets, [])
How?
s2ZFṢ$€E¬,L - Link 1, get (isUnfair, Slices): A possible partition
s2          - split into slices of length 2 (any odd one on it's own at the end)
  Z         - transpose (first item is one thief's slices, second is the others)
     $€     - last two links as a monad for €ach
   F        -     flatten
    Ṣ       -     sort
       E    - equal? (theif1's jewels == theif2's jewels)
        ¬   - not
          L - length (number of slices in the partition)
         ,  - pair

ŒṖṖÇÞḢ - Main link: necklace
ŒṖ     - all partitions
  Ṗ    - pop, we must remove the rightmost one...
              because Link 1 will say it is fair, and it will have length 1!
              (a list of one thing has all entries equal)
    Þ  - sort by
   Ç   -     last link (1) as a monad
     Ḣ - head (get the first one, i.e. minimal isUnfair, then minimal length)

Mathematica, 118 bytes
Almost beat Jelly ... just 1 off ;)
SelectFirst[l_±c_:=Append[-#±Most@c,#2]&@@l~TakeDrop~Last@c;l_±{}:={l};i=#;(i±#)&/@Range@#2~Subsets~#3,Tr[Tr/@#]==0&]&

Pure function taking three arguments: the necklace, as a list of tokens such as {A, A, A, A, B, C, D, B, C, D, B, B}; the length of the necklace; and the number of distinct jewel times. It returns a list of sublists in the form {{A, A}, {-A, -A, -B, -C, -D, -B}, {C, D, B, B}}, where the tokens without negative signs go to one thief and the tokens with negative signs go to the other thief. (While this is redundant information, the algorithm leads to this representation, and removing the negative signs would cost several bytes.)
First we have to implement a function that takes a list and a set of n cut-places and returns the list of n+1 sublists obtained by cutting the input list at those n cut-places; the binary infix operator ± is used for this purpose, and defined recursively through l_±c_:=Append[-#±Most@c,#2]&@@l~TakeDrop~Last@c;l_±{}:={l};. Because of the negative sign right after Append, the result is that the sublists alternately do and do not have negative signs attached to each token.
Then we generate all possible cut-place sets whose length is at most the number of jewel types, using Range@#2~Subsets~#3, and use i=#;(i±#)&/@ to apply the ± operator (with the input list of jewels) to each of these cut-place sets in turn.
Finally, SelectFirst[...,Tr[Tr/@#]==0&]& picks out the first of the resulting necklace divisions that is fair. It does so by literally adding up all of the elements in all of the sublists; Mathematica is wise enough to cancel the positive and negative copies of each token in the obvious way.

Pyth, 16 bytes
hfqFSMsM.TcT2t./

Try it online: Demonstration or Test Suite
Explanation:
hfqFSMsM.TcT2t./Q   implicit Q (=input) at the end
              ./Q   create all partitions of the input list
                    (they are already sorted by number of cuts)
             t      remove the partition with zero splits
 f                  filter for partitions T, which satisfy:
          cT2          chop into pieces of length 2
        .T             transpose to get the pieces of each thieve
    SMsM               combine all pieces for each thieve and sort the results
  qF                   check if they got the same jewels
h                   print the first such partition

05AB1E, 14 bytes
.œ¨ʒ2ôζε˜{}Ë}¤

Try it online or verify all test cases.
Explanation:
.œ                # All partitions of the (implicit) input
                  #  i.e. [2,3,2,1,3,1]
                  #   → [[[2],[3],[2],[1],[3],[1]],[[2],[3],[2],[1],[3,1]],
                  #      ...,[[2,3,2,1,3,1]]]
  ¨               # Remove the last one
   ʒ        }     # Filter this list by:
    2ô            # Split it into parts of 2
                  #  i.e. [[2,3],[2],[1],[3,1]] → [[[2,3],[2]],[[1],[3,1]]]
                  #  i.e. [[2,3,2],[1,3],[1]] → [[[2,3,2],[1,3]],[[1]]]
      ζ           # Swap rows and columns (using space as filler if necessary)
                  #  i.e. [[[2,3],[2]],[[1],[3,1]]] → [[[2,3],[1]],[[2],[3,1]]]
                  #  i.e. [[[2,3,2],[1,3]],[[1]]] → [[[2,3,2],[1]],[[1,3]," "]]
       ε  }       # Map each inner list to:
        ˜         # Flatten the list
                  #  i.e. [[2,3],[1]] → [2,3,1]
                  #  i.e. [[1,3]," "] → [1,3," "]
         {        # Sort the list
                  #  i.e. [2,3,1] → [1,2,3]
                  #  i.e. [1,3," "] → [1,3," "]
           Ë      # Check if both sorted lists are equal
                  # (if not, remove them from the partitions)
             ¤    # After filtering, take the last one as result (and output implicitly)
                  #  i.e. [[[2],[3,2],[1,3],[1]],[[2,3],[2],[1],[3,1]]]
                  #   → [[2,3],[2],[1],[3,1]]

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


text:
Is today a real weekday?
Feb. 6 was a real weekday. Because it lies in the 6th week of the year.
So a real weekday is a day with a a day number that equals the week number.
But not all country have the same counting of weeks. in Germany a week starts with Monday and ends on Saturday in the US they start on Sunday.
Write a program that checks a given date (the format your program likes the best) and a weekstart ('S' or 'M') whether it is a real weekday.
Too simplify things a bit we assume January 1st is always a real weekday because it is in the first week. In Germany it is the last day of week 52)
Some examples of real weekday for a start on Monday:
 2017-01-01
 2017-02-07
 2017-04-17

Some examples of real weekday for a start on Sunday:
2017-01-01
2017-02-06
2017-04-16

Example:
2017-04-16 S Output: YES
20170416M Output: 0

How you enter the Date does not matter, as long as it is human readable. The start day can be given by M or S or 1 or 0.
the Output is a printed boolean Yes, not or Y,N or 0,1
Shortest code wins!
Its my first question I put on this forum, so I'd be happy to hear some comments.

It's not clear. Can our program use either Sunday or Monday start days or does it have to accept a second input and handle both

Could you provide more clear examples of input and output?

@Suever, seems like no, as he writes "checks a given date ... and a weekstart".

Could you confirm "the first week of 2017 for a start of "Monday" is just one day long, having the second week start on Monday the 2nd"?

@Jonathan: yes that is true!

Hi and welcome to PPCG! I think this is an interesting enough question, there are just a few points that need to be made a bit more clear, so I've voted to close this question as unclear in the meantime. In the future, I strongly recommend making use of the Sandbox where you can post challenges and get meaningful feedback before posting them to main. Welcome to the site!

I added a bit of explanation for  the valid input.

"Feb. 6 was a real weekday. Because it lies in the 6th week of the year. So a real weekday is a day with a day number that equals the week number." How I interpret this is: real_weekday: week_of_year == day_of_month. But what does this have to do with the day of the week? A year is just 52 weeks, and the week_of_year is based on that like an index. So it shouldn't matter whether it's Monday, Sunday, or Wednesday, unless I'm misinterpreting something here.. :S

@KevinCruijssen the week starts on sunday/monday, for example 2016-01-01 was a friday , so it was in the 53th week of 2015, the 1st week of 2016 started on 03(or 04) of january

So in Germany are weeks only 6 days long?

@Rod - that is not quite the case, see my question, above. The second week of 2016 started on the 3rd/4th

So this is just false for anything after the 31st week in the year?

@carusocumputing thats true; after the 31st week ther is nor real week day

@Kevin,@LLiw Week are complicated. I tried to simplify the question for the two types I know. Weeks starting on Sunday and Weeks starting on Mondays (ending on Sundays) and that January the 1st is always on the first week of the new year.
In Germany (and in Europe) it's a bit more complicated. The first week of the year is the week containing Jan 4th. So Dec 31st can be on Week 1 and Jan 1st can be on week 52, (Sometimes even week 53 like in 2005 and 2010). BTW: Its not a funny oddity its international standard.(ISO 8601).

MATLAB, 53 bytes
d=datetime(input(''));week(d-(input('')=='M'))==d.Day

This answer accepts the first input as a string '2017-02-06' and the second input as a string (either 'S' or 'M').

It constructs a datetime object from the first input and saves it in d. We then compute the week number (but first we subtract 1 day from the date if the second input is an 'M' since week uses Sundays by default) and then we compare this week number to the day of the datetime object to yield a boolean.

Great! But where do you specify whether the week starts with Sunday or Monday?

@JoachimWeiß Fixed.


text:
Your Base to 1-2-3-Tribonacci to Binary back to Your Base
Background
The 1-2-3-Tribonacci Sequence
Imagine for a second that you could make a fibonacci sequence by replacing the standard iteration formula with the following:

Basically, instead of summing the last two to get the next, you sum the last three. This is the basis for the 1-2-3-Tribonacci sequence.
Brown's Criterion
Brown's Criterion state that you may represent any integer value as a sum of members of a sequence provided that:

For all n greater than 1,

What this means for the challenge
You may describe any positive integer as a sum of members of the 1-2-3-Tribonacci sequence formed by the following initial conditions:

This is known as, for every value in this sequence, the ratio between terms is never greater than 2 (the ratio averages out at about 1.839).
How to write in this numerical representation system
Let's say that you use a little-endian representation. Line up members of the sequence like so:
1  2  3  6 11 20 37 68

Then, you take your number to be represented (for our tests, let's say it's 63) and find the values of the given 1-2-3-Tribonacci which sum to 63 (using the largest values first!). If the number is part of the sum, put a 1 under it, 0 if not.
1  2  3  6 11 20 37 68
0  0  0  1  0  1  1  0

You may do this for any given integer - just verify that you use the largest values below your given input first!
Definition (finally)
Write a program or function that will do the following given some positive integer input n (written in any standard base) between 1 and your language's maximum value:

Convert the value into the defined 1-2-3-Tribonacci's numerical representation.
Using this binary-like representation, and read it as if it were binary. This means that the digits stay the same, but what they mean changes.
Take this binary number and convert it into the base of the original number.
Output or return this new number.

However, as long as the output is valid, you needn't follow these steps. If you magically find some formula that is shorter (and mathematically equivalent), feel free to use it.
Examples
Let the function f be the function described by the definition, and let [] represent steps taken (as little-endian, though it shouldn't matter) (you do not need to follow this process, this is just the process described):
>>> f(1)
[1]
[1]
[1]
1

>>> f(5)
[5]
[0, 1, 1]
[6]
6

>>> f(63)
[63]
[0, 0, 0, 1, 0, 1, 1]
[104]
104

Can I submit a separate program which while not as short will solve the question faster? log(log(n))+n time as opposed to log(n)+n time. Go go Nth power matrix.

@LliwTelracs I cannot stop you from posting your solutions. Just make that solution method target as concise to your knowledge as you can to make sure you're competing in the right field still.

Well, not going to do this one at least. Fast exponentiation of this matrix is ridiculously verbose

@LliwTelracs Maybe just add it as an addendum to your existing post then.

your challenge is illegible for those that can't show images.

Unfortunately, all my base are belong to somebody else, and I don't think it would be a good idea to change them without consulting the owner.

This could use a few more test cases. I'd add at least 2 to 10 (quite a few edge cases there) and 231 (first input for which output > 2 × input).

Javascript 117 111 bytes
Thanks to @theonlygusti for helping golf off 5 bytes
x=>{r=0;a=[1,2,3];i=1;while(a[++i]<x)a[i+1]=a[i]+a[i-1]+a[i-2];for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}return r}

How It Works
First, the function generates all tribonacci numbers until it finds one greater than the input
a=[1,2,3];i=1;for(;a[++i]<x;)a[i+1]=a[i]+a[i-1]+a[i-2];

Next, it reverse searches the list of numbers. If a number is less than the input, it adds 2^(index of that number) to the return value and reduces the input by that number.
for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}

Finally it returns the result.
Try it Online

what about a[++i]<x inside the for condition to save a byte?

Also, you can replace x>0 with x. Save another 2 bytes.

That's a pretty good algorithm. o.o

Python 2, 110 102 bytes
-3 bytes thanks to Rod (neat trick for casting boolean i to an int with +i so the repr `+i` works)
n=input()
x=[3,2,1]
r=''
while x[0]<n:x=[sum(x[:3])]+x
for v in x:i=n>=v;n-=v*i;r+=`+i`
print int(r,2)

Try it online!

you can replace '01'[i] with \+i``

i is a boolean not an int. Edit - Ohhh +i, neat.

@Rod Is that trick in the Python 2 tips and tricks?

@VoteToClose I don't think so

JavaScript (ES6), 97 93 bytes
Here, we are using reduce() on a recursive function. We assume that the output is 31-bit (which is the largest unsigned quantity that JS can easily work with for bitwise operations anyway).
n=>[...Array(x=31)].reduce(p=>(c=(F=k=>k<4?k:F(--k)+F(--k)+F(--k))(x--))>n?p:(n-=c,p|1<<x),0)

Performance wise, this is clearly not very efficient.
For the curious:

The ratio between the number of calls to F() for N+1 reduce() iterations vs N iterations quickly converges towards the Tribonacci Constant (≈ 1.83929). Therefore, each additional bit in the output costs approximately twice as much time as the previous one.
With 31 bits, the F() function is called a good 124 million times.

Test
NB: This may take 1 or 2 seconds to complete.

let f =

n=>[...Array(x=31)].reduce(p=>(c=(F=k=>k<4?k:F(--k)+F(--k)+F(--k))(x--))>n?p:(n-=c,p|1<<x),0)

console.log(f(63))

Wow, that lags my browser when I use it. xD

@VoteToClose Performance wise, this is dreadfully inefficient. :-) The test code should not lag for too long, though. On my box, I get about 600ms in Firefox and 900ms in Chrome. Is it much slower on your side?

Like, 5 seconds. xD

@VoteToClose Should be a bit faster now. The 32nd iteration was pointless, so I've limited the output to an unsigned 31-bit integer.

Mathematica, 78 74 bytes
Fold[#+##&,#~NumberDecompose~Reverse@LinearRecurrence[{1,1,1},{1,2,3},#]]&

LinearRecurrence[{1,1,1},{1,2,3},#] generates a list, of length equal to the input, of the 1-2-3 tribonacci numbers. (The {1,1,1} represents the sum of the previous three terms, while {1,2,3} are the initial values.) Then #~NumberDecompose~ finds the greediest way to write the input as a sum of elements of the list (this is the same function that would decompose a monetary amount into multiples of the available currencies, for example). Finally, Fold[#+##&,...] converts the resulting binary list into a (base-10) integer.
Previous submission:
Fold[#+##&,#~NumberDecompose~Reverse@Array[If[#<4,#,Tr[#0/@(#-Range@3)]]&,#]]&

As is often the case (though not above), this golfed version is super slow on inputs larger than 20 or so, because it generates (with non-optimized recursion) a list of tribs whose length is the input; replacing the final # by a more reasonable bound like Round[2Log@#+1] results in much better performance.

Whaat? Mathematica doesn't have an 123Tribonacci[] builtin?

Not exactly, although it turns out that using a builtin does help a bit.

Haskell, 95 bytes
(a!b)c=a:(b!c)(a+b+c)
e#(r,c)|c-e<0=(2*r,c)|1<2=(2*r+1,c-e)
f n=fst$foldr(#)(0,n)$take n$(1!2)3

Usage example: f 63 -> 104. Try it online!.
How it works: ! builds the 1-2-3-Tribonacci sequence. Given 1, 2 and 3 as the start parameters, we take the first n elements of the sequence. Then we fold from the right function # which subtracts the next element e from n and sets the bit in the return value r if e is needed or lets the bit unset. Setting the bit is doubling r and adding 1, letting it unset is just doubling.

Jelly, 31 bytes
S=³
3RUµḣ3S;µ<³Ạµ¿µŒPÇÐfṀe@Ð€µḄ

Try it online!
I'm almost certain there is a MUCH shorter way to achieve this in Jelly.
How?
S=³ - Link 1, compare sum to input: list
S   - sum
  ³ - 3rd command line argument which is 1st program argument.
 =  - equal?

3RUµḣ3S;µ<³Ạµ¿µŒPÇÐfṀe@Ð€µḄ - Main link: n
3RU                         - range(3) upended -> [3,2,1]
   µ    µ   µ¿              - while
         <³                 - less than input (vectorises)
           Ạ                - all?
    ḣ3S;                    -     head(3), sum, and concatenate
                                  [3,2,1] -> [6,3,2,1] -> [11,6,3,2,1] -> ...
              µ             - monadic chain separation, call the result x
               ŒP           - power set of x - e.g. for [6,3,2,1] -> [[],[6],[3],[2],[1],[6,3],[6,2],[6,1],[3,2],[3,1],[2,1],[6,3,2],[6,3,1],[6,2,1],[3,2,1],[6,3,2,1]]
                  Ðf        - filter keep
                 Ç          -     last link (1) as a monad (those that sum to the input)
                    Ṁ       - maximum (e.g. an input of 63 would yield [[37,20,6],[37,20,3,2,1]], the maximum of which is [37,20,6], the one with the largest numbers used)
                         µ  - monadic chain separation (to have x as the right argument below)
                     e@Ð€   - exists in with reversed arguments mapped over x (e.g. [37,20,6] with x = [68,37,20,11,6,3,2,1] yields [0,1,1,0,1,0,0,0])
                          Ḅ - convert from binary to integer.

Perl 6, 93 91 bytes
-2 bytes thanks to b2gills
{my@f=1,2,3,*+*+*...*>$^n;sum @f».&{$_~~any first *.sum==$n,@f.combinations}Z*(2 X**^∞)}

How it works

First, it generates the 1-2-3-Tribonacci sequence up to the first element larger than the input:
my @f = 1, 2, 3, *+*+* ... * > $^n;
Based on that it finds the subset of the sequence which adds up to the input:
first *.sum==$n, @f.combinations
Based on that it constructs a list of booleans specifying whether each element of the sequence is part of the sum:
@f».&{$_~~any ...}
And finally it interprets that list of True=1, False=0 values as base 2 and returns it as a (base 10) number:
sum ... Z* (2 X** ^∞)

You can shorten it by using *>$^n and .sum==$n. Also the space isn't needed between my and @f

JavaScript (ES6), 61 60 bytes
n=>(g=(x,y,z)=>(n>x&&g(y,z,x+y+z)*2)+!(n<x||![n-=x]))(1,2,3)

Calculates the 1-2-3-Tribonacci numbers until it reaches the original number, then as the recursion unwinds, tries to subtract each one in turn, doubling the result as it goes.
Edit: Saved 1 byte thanks to @Arnauld.

Wow! Very nice. Could n=>(g=(x,y,z)=>(n>x&&g(y,z,x+y+z)*2)+!(n<x||![n-=x]))(1,2,3) save a byte?

@Arnauld I had been looking for something using n<x|| but that ![] is just genius.

Jelly, 19 18 17 bytes
Ḣx3+
BÇL¡2ị
²Ç€»ċ

Try it online!
Background
Instead of trying to convert an integer to 1,2,3-Tribonacci base, then from binary to integer, we'll do the opposite: convert integers to binary, then from 1,2,3-Trionacci base to integer, and return the highest one that matches the input. This is easily accomplished.
We'll exemplify the process for input 63, in particular the step where 104 is tested. In binary, from most significant to least significant digit, 104 is equal to
 1  1  0  1  0  0  0
37 20 11  6  3  2  1

where the second row represents the positional values of those digits.
We can extend the 1,2,3-Tribonacci sequence to the right, observing that the added digits comply with the same recursive formula. For three mre digits, this gives
 1  1  0  1  0  0  0  0  0  0
37 20 11  6  3  2  1  0  1  0

Now, to compute the value of the base 1,2,3-Tribonacci number, we can make use of the recursive formula. Since each number is the sum of the three numbers to its right (in the table above), we can remove the first digit and add this to the first three digits of the remaining array. After 7 steps, which is equal to the number of binary digits of 104, we rare left with only three digits.
 1  1  0  1  0  0  0  0  0  0
37 20 11  6  3  2  1  0  1  0

    2  1  2  0  0  0  0  0  0
   20 11  6  3  2  1  0  1  0

       3  4  2  0  0  0  0  0
      11  6  3  2  1  0  1  0

          7  5  3  0  0  0  0
          6  3  2  1  0  1  0

            12 10  7  0  0  0
             3  2  1  0  1  0

               22 19 12  0  0
                2  1  0  1  0

                  41 34 22  0
                   1  0  1  0

                     75 63 41
                      0  1  0

Now, since the first and last remaining digit both have positional value 0, the result is the middle digit, i.e, 63.
How it works
²Ç€»ċ   Main link. Argument: n

²       Yield n². Since 1.839² = 3.381921 > 2, the range [1, ..., n²] will contain
        the answer. Better bounds, at the cost of additional bytes are possible.
 Ç€     Map the the second helper link over [1, ..., n²].
   »    Take the maximum of n and each result.
    ċ   Count the occurrences of n.

BÇL¡2ị  Second helper link. Left argument: k. Right argument: n

B       Convert k to binary. Let's call the result A.
  L     Length; count the number of binary digits. Let's call the result l.
 Ç ¡    Apply the first helper link l times to A.
    2ị  Retrieve the second element.

Ḣ×3+    First helper link. Argument: A (array)

Ḣ       Head; pop and yield the first element of A.
 x3     Repeat it thrice.
   +    Add the result, component by component, to the beheaded A.

Batch, 151 148 145 bytes
@set/ar=0,n=%1
@call:c 3 2 1
@echo %r%
@exit/b
:c
@set/as=%1+%2+%3
@if %n% gtr %3 call:c %s% %*
@set/ar*=2
@if %n% geq %3 set/an-=%3,r+=1

Port of my JavaScript answer. Edit: Saved 3 bytes by passing my subroutine arguments in reverse order and another 3 bytes by using individual @s on each line instead of @echo off.

Jelly (fork), 17 16 bytes
ḣ3S;µ¡
3RṚÇ³æFṪḄ

Saved 1 byte thanks to @Dennis who golfed it without even running it.
This relies on a fork of Jelly where I am disappointingly still working on implementing an efficient Frobenius solve atom. For those who are interested, I would like to match Mathematica's speed in FrobeniusSolve and luckily there is an explanation of their method in the paper "Making Change and Finding Repfigits: Balancing a Knapsack" by Daniel Lichtblau.
Explanation
ḣ3S;µ¡  Helper link. Input: a list
    µ   Create monadic chain
ḣ3        Take the first 3 items
  S       Sum
   ;      Prepend to the list
     ¡  Repeat it n (initial argument from main) times

3RṚÇ³æFṪḄ  Main link. Input: integer n
3          The constant 3
 R         Range. Makes [1, 2, 3]
  Ṛ        Reverse. Makes [3, 2, 1]
   Ç       Call the helper link on that list.
           Generates the first (n+3) 123-Tribonacci values in reverse
    ³      Get n
     æF    Frobenius solve for n using the first n 123-Tribonacci values in reverse
       Ṫ   Tail. Take the last value. The results of Frobenius solve are ordered
           where the last result uses the least
        Ḅ  Unbinary. Convert digits from base 2 to base 10

You know that you're getting deep into the code golf when you're using forks of super-esolangs.

Would ḣ3S;µ¡¶3RṚÇ³æFṪḄ work? I don't have your fork installed, so I can't test.

@Dennis That is taking input from stdin not arguments, right? I was having trouble using arguments and just realized it worked the other way.

No, that should still be arguments. ³ references the first argument.

@Dennis Nvm, it does work by arguments, my jelly.py had some other things in it after that last commit.

dc, 110 102 bytes
?se1sa2sb3sc_1sf[laddSdlbdsalcdsb++sclf1+sfle>y]dsyx0sk[lk2lf^+skler-se]sr[Lddle!<rlf1-dsf0!>z]dszxlkp

Well, seems like great minds do think alike. Apparently, the algorithm I came up with to get around the limitations of dc is coincidentally the exact same one used in @LliwTelrac's answer. Interesting.
Try it online!

Python 2, 93 bytes
n=input();y=k=n*n
while y>n:
 x=y=z=0;k-=1
 for t in bin(k):x+=t=='1';x,y,z=y+x,z+x,x
print k

This is a port of my Jelly answer.
Try it online!

bash + BSD utilities (OS X, etc.), 53 bytes
jot $[2#$1**4]|egrep -v '[2-9]|11(1|$)'|sed $[2#$1]!d

bash + GNU utilities (works under BSD also), 59 bytes
seq -f2o%.fp $[2#$1**2]|dc|egrep -v '11(1|$)'|sed $[2#$1]!d

Input and output in both the above are in binary.

Try out the GNU version at TIO.  (The example linked to demonstrates input of 111111, which is 63 in binary, and output of 1101000, which is 104 in binary.)
I don't think TIO offers a BSD option, but if you have a Mac available, you can try them both out there.  (The 59-byte program is much faster than the 53-byte program.)

Unfortunately, seq can't simply be dropped into the BSD solution in place of jot, since the output format for seq is different for outputs above 999999.  (This starts being a problem for inputs around 32, since 32^4 > 1000000.)
You can replace jot above with seq -f%.f to get this to work with GNU utilities, but for the same 59 bytes, you can use the GNU solution above, which is much faster.


text:
Tips for golfing in SmileBASIC
SmileBASIC deserves more attention. I've only seen 3 users here (including myself!) providing SB answers, and while that doesn't surprise me, it disappoints me. It being a paid lang as well as being a BASIC dialect certainly turns people off, but for those who own it it's actually pretty flexible and, surprisingly, golfable. I figured I'd open this tips thread for it and see what comes up.
I expect 12Me21 to visit frequently :)

Replace string!="" with string>""
SB allows you to do greater/less comparisons on strings, based on their codepoints. However, the empty string is considered the smallest string there is.
So for situations where you do string!="" you can use either string>"" or ""<string, since every string is greater than "" and "" is less than every string. Depending on whether you use < or > depends on if the statement needs whitespace before or after to be valid syntax, which can also save you bytes.
For example:
WHILE S$!=""

can be turned into
WHILE S$>""

and further golfed to
WHILE""<S$

All strings are truthy. Even empty ones.

Ah, okay. Makes sense.

Using ?, ., @, and unclosed strings
Many dialects of BASIC support ? for printing, and SB is no exception. Having an extremely short text output function is a big advantage.
In SmileBASIC, . is evaluated to 0.0, so it can be used in place of 0 to save space. For example:
SPSET 0,21 can be SPSET.,21, saving 1 byte. (SPSET0,21 is invalid because SPSET0 could be a user defined function)
EXEC. is an extremely short way to make a program loop forever (but it resets all your variables, so it's not always usable)
Labels (used for GOTO, GOSUB, and reading DATA) are represented as @LABEL in SmileBASIC. When used in an expression, they are actually treated as strings. For example, BGMPLAY"@305C" can be written as BGMPLAY@305C
Strings are automatically closed at the end of a line (or the end of the program). ?"Hello, World!" can be written as ?"Hello, World!. This can also be used to make programs more readable by splitting them into multiple lines without changing the length: ?"Meow"BEEP 69 can be
?"Meow
BEEP 69

Wow, using labels to start MML is insane. Would've never thought of that, though it does limit your character set.

Another place I used it was to check if a hexadecimal digit was a number or a letter: @A<POP(H$) is shorter than "@"<POP(H$) (the A doesn't matter, it only ever checks the first character since it will never be the same)

Use string indexing instead of MID$
The MID$ function is a common function in many BASICs to get a substring from somewhere in the middle of a string. However, if you just need to get the character at some index, using string indexing is far shorter. For example:
PRINT MID$("ABC",2,1)
PRINT "ABC"[2]

Both of these print C. Strings support array-like indexing on a character basis, so if you only need to check one character at a time, this is the best way to do it.

You should talk about how strings can be modified this way. A$=@AA:A$[2]="BD":A$[0]="":A$[2]="C"

I'll probably write a set of answers about how strings are basically character arrays but even better, because putting it all into one is quite a task.

...or you could write some ;)

I'm not very familiar with how it works in other languages.

Use the syntax highlighter!
SmileBASIC's code editor has a built in syntax highlighter, that can be used to determine whether code will work or not.
For example, if you try to do BEEP0, it will not highlight it, because there needs to be a space between a function and a digit. However BEEP. works, because . is not a digit.
Normally code like X=7BEEP is valid, since functions can't start with a number, so SB assumes that 7 and BEEP are separate. However. X=7END is NOT allowed (and not highlighted), because it tries to interpret 7E... as a number, but since there's no digit after the E, it fails, causing an error. Normally this would be pretty hard to figure out, but with a very reliable syntax highlighter, it's much easier to tell what you can and can't do.
My SmileBASIC syntax highlighter is designed to (hopefully) perfectly match the behavior of SB, so you can use it to check if code is valid.

<!DOCTYPE html>

  <meta charset="utf-8">

  <link rel="stylesheet" type="text/css" href="https://12Me21.github.io/sbhighlight3/style.css">
  <link rel="stylesheet" type="text/css" href="https://12Me21.github.io/external/smilebasicfont.css">

  Use SB font:<input type="checkbox" autocomplete="off" onchange="$code.dataset.sbfont=$input.dataset.sbfont=this.checked;update()"></input>
  <button onclick="update()">force update</button>

test

test

When to use : (or not)
The : character is used as a statement-breaker in SB. Basically, you use it to stack statements on one line like so:
PRINT "HELLO!":PRINT "GOODBYE!"

Otherwise, your average statement is broken by a newline:
PRINT "HELLO!"
PRINT "GOODBYE!"

In reality, you often don't need to use the colon at all. So long as statements can be broken into syntactically valid tokens, the parser tends to figure out when one ends and the other starts. The same often goes for whitespace.
PRINT"HELLO!"PRINT"GOODBYE!"

Of course, this doesn't always work. There are always ambiguous cases and invalid syntaxes where you have to explicitly break statements. Take for example:
PRINT "HELLO";END

The semicolon means that PRINT is expecting another expression to print out, unless the statement breaks there (we use dangling semicolons to suppress the newline.) Here it assumes END is supposed to be a value, despite being a keyword, and tries to print it, resulting in an error. Thus, we have to explicitly break this statement, be it the colon or the newline.
In general, if something seems ambiguous, try it to see if it works. If it doesn't, break the statement. In addition, anything that would produce invalid syntax isn't highlighted correctly as 12Me21 mentioned.

Avoid the MOD operator
The modulus operator is really long, and should be avoided if possible.
If you're getting characters from a string, you can just repeat the string instead:
"ABC"[X MOD 3]
("ABC"*9)[X] (assuming X will always be less than 27)

Sometimes you can save 1 character with AND instead:
X MOD 4
3AND X

Omitting OUT return values
An OUT form function is one with multiple returns; you specify the variables to accept the return values after the OUT keyword. An example using DTREAD:
DTREAD OUT yearVar,monthVar,dayVar

But what if you only want one of the values, like the current month? You can "ignore" the rest of the values by simply not writing any variable name to accept them! You do, however, have to leave in the commas (aside from the occasional optional return.)
DTREAD OUT ,monthVar,

Which can be further golfed to
DTREAD OUT,M,

Use LAST()
Now that SmileBASIC 4 is out in Japan, we can check out some of the potential golf savings. One that immediately jumps out to me is the new LAST() function, which returns the last index of an array or string. You can save one byte.
LEN(v)-1 'old way
LAST(v)  'new way


text:
Output numbers up to 2^n-1, "sorted"
Take a positive integer n as input, and output (some of the) decimal numbers that can be created using n bits, ordered in the following way:
First list all the numbers that can be created with only one 1, and the rest 0 in the binary representation (sorted), then all the numbers that can be created with two consecutive 1, the rest 0, then three consecutive 1 and so on.
Let's see what this looks like for n=4:
0001  -  1
0010  -  2
0100  -  4
1000  -  8
0011  -  3
0110  -  6
1100  -  12
0111  -  7
1110  -  14
1111  -  15

So, the output for n=4 is: 1, 2, 4, 8, 3, 6, 12, 7, 14, 15 (optional output format).
Test cases:
n = 1
1

n = 2
1 2 3

n = 3
1, 2, 4, 3, 6, 7

n = 8
1, 2, 4, 8, 16, 32, 64, 128, 3, 6, 12, 24, 48, 96, 192, 7, 14, 28, 56, 112, 224, 15, 30, 60, 120, 240, 31, 62, 124, 248, 63, 126, 252, 127, 254, 255

n = 17
1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 3, 6, 12, 24, 48, 96, 192, 384, 768, 1536, 3072, 6144, 12288, 24576, 49152, 98304, 7, 14, 28, 56, 112, 224, 448, 896, 1792, 3584, 7168, 14336, 28672, 57344, 114688, 15, 30, 60, 120, 240, 480, 960, 1920, 3840, 7680, 15360, 30720, 61440, 122880, 31, 62, 124, 248, 496, 992, 1984, 3968, 7936, 15872, 31744, 63488, 126976, 63, 126, 252, 504, 1008, 2016, 4032, 8064, 16128, 32256, 64512, 129024, 127, 254, 508, 1016, 2032, 4064, 8128, 16256, 32512, 65024, 130048, 255, 510, 1020, 2040, 4080, 8160, 16320, 32640, 65280, 130560, 511, 1022, 2044, 4088, 8176, 16352, 32704, 65408, 130816, 1023, 2046, 4092, 8184, 16368, 32736, 65472, 130944, 2047, 4094, 8188, 16376, 32752, 65504, 131008, 4095, 8190, 16380, 32760, 65520, 131040, 8191, 16382, 32764, 65528, 131056,16383, 32766, 65532, 131064, 32767, 65534, 131068, 65535, 131070, 131071

This is code-golf, so the shortest code in each language wins!
Good explanations are highly encouraged, also for solutions in "regular languages"!

A dup of http://codegolf.stackexchange.com/q/98322/61904 ?

@zeppelin I thought so too at first, but this one is very different.

Related. (Slightly.)

Imaginary bonus if someone does this without any form of base conversion (using plain old maths).

Wrote this which is a mix between the two I guess Try it online!

Python, 53 bytes
f=lambda n,i=1:n*[f]and[i]+f(n-1,2*i)+i%2*f(n-1,i-~i)

Try it online!
The recursive function generates the sorted list as a pre-order walk down this tree (example with n=4):
      1
     / \
    2   3
   /   / \
  4   6   7
 /   /   / \
8   12  14  15

1 2 4 8 3 6 12 7 14 15

Left branches double the value, and right branches do i->i*2+1 and exist only for odd i. So, the pre-order walk for non-leaves is T(i)=[i]+T(i*2)+i%2*T(i*2+1).
The tree terminates at depth n, where n is the input. This is achieved by decrementing n with each step down and stopping when it is 0.
An alternative strategy would be to terminate on values that i exceeds 2**n, rather than tracking depth. I found this to be one byte longer:
f=lambda n,i=1:2**n/i*[f]and[i]+f(n,2*i)+i%2*f(n,i-~i)
f=lambda n,i=1:[f][i>>n:]and[i]+f(n,2*i)+i%2*f(n,i-~i)

Wow. Not only is that a really cool/clever trick, but it's extremely effective. +1, really nice answer!

The [f] is an amusing touch, can't say I've seen that before.

Jelly, 6 bytes
Ḷ2*ẆS€

This qualifies for the imaginary bonus.
Try it online!
How it works
Ḷ2*ẆS€  Main link. Argument: n

Ḷ       Unlength; yield [0, ..., n-1].
 2*     Yield [2**0, ..., 2**(n-1)].
   Ẇ    Sliding window; yield all subarrays of consecutive elements.
        The subarrays are sorted by length, then from left to right.
    S€  Map the sum atom over the substrings.

Ẇ is an ideal built-in for this challenge, and it's implemented so that the results are in just the right order for this challenge. Well done :-)

Isn't this 12 bytes (at least in UTF-8)?

@Gareth Yes, but Jelly also supports a single byte character set, which contains the only 256 symbols it understands.

Mathematica, 40 bytes
Join@@Table[2^j(2^i-1),{i,#},{j,0,#-i}]&

Every number in the desired list is the difference of two powers of 2, so we simply generate them in order using Table and then flatten the list. I think this earns Stewie Griffin's imaginary bonus :)
Mathematica, 35 bytes
Tr/@Rest@Subsequences[2^Range@#/2]&

A port of Dennis's Jelly algorithm. I didn't know about Subsequences before this! (I also didn't see that miles had posted this exact answer ... go upvote it!)

Note: This solution is identical to @mile 's Mathematica code, posted 5 hours before @GregMartin 's edit. However, per meta consensus, this answer is still valid.

Ugh, I didn't see that—thanks for pointing it out.

JavaScript (ES6), 59 58 55 bytes
for(q=prompt(n=1);p=q--;n-=~n)for(m=n;p--;m*=2)alert(m)

A full program that takes input through a prompt and alerts each number in succession. This also qualifies for the imaginary bonus.
Test snippet
(Note: uses console.log instead of alert)

for(q=prompt(n=1);p=q--;n-=~n)for(m=n;p--;m*=2)console.log(m)

Suggestion(after having to check "dont show anymore popups"): Change to console.log for the test snippet.

@TejasKale Good idea, thanks!

JavaScript (ES6), 55 51 bytes
Returns a space-separated list of integers.
n=>(F=k=>k>>n?--j?F(k>>j|1):'':k+' '+F(k*2))(1,j=n)

Imaginary bonus friendly.
Formatted and commented
n => (                    // main function, takes n as input
  F = k =>                // recursive function, takes k as input
    k >> n ?              // if k is greater or equal to 1 << n:
      --j ?               //   decrement j ; if j is > 0:
        F(k >> j | 1)     //     do a recursive call with an additional bit set
      :                   //   else
        ''                //     stop recursion
    :                     // else
      k + ' ' + F(k * 2)  //   append k to output and do a recursive call with k * 2
  )(1, j = n)             // start the recursion with k = 1 and j = n

Test cases

let f =

n=>(F=k=>k>>n?--j?F(k>>j|1):'':k+' '+F(k*2))(1,j=n)

console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(8))
console.log(f(17))

Python 2, 64 61 bytes
-3 bytes thanks to Dennis

n=2**input()
j=i=1
while j<n:
 print i;i*=2
 if i/n:i=j=2*j+1

Try it online!

Mathematica, 35 bytes
Tr/@Rest@Subsequences[2^Range@#/2]&

Python 2, 65 63 58 bytes
lambda n:[(2<<k/n)-1<<k%n for k in range(n*n)if k/n+k%n<n]

Try it online!

I just spent an hour coming up with that formula (2<<i)-1<<j ... and you've already figured it out. Great job! Also, good job at getting rid of the double ranges

Haskell, 37 bytes
f n=[2^b-2^(b-a)|a<-[1..n],b<-[a..n]]

Try it online!

Groovy, 90 89 bytes
{(0..<2**it).collect{0.toBinaryString(it)}.sort{it.count("1")}.collect{0.parseInt(it,2)}}

Binary conversion is so dumb in groovy.
-1 thanks to Gurupad Mamadapur

28 bytes binary conversion boilerplate, so painful.

{(1..<2**it)... saves a byte.

Haskell, 47 bytes
f n=[1..n]>>= \b->take(n-b+1)$iterate(2*)$2^b-1

Usage example: f 4 -> [1,2,4,8,3,6,12,7,14,15]. Try it online!.
How it works: for each number b in [1..n], start with 2^b-1 and repeatedly double the value and take n-b+1 elements from this list.

05AB1E, 6 bytes
L<oŒéO

Try it online!
or as a Test suite
Explanation
Uses the sublist-sum trick as shown in Dennis' Jelly answer
L       # range [1 ... input]
 <      # decrement each
  o     # raise 2 to each power
   Œ    # get all sublists
    é   # sort by length
     O  # sum

Pyth, 7 bytes
sM.:^L2

Try it online.
Uses Dennis's algorithm.

Bash + Unix utilities, 51 bytes
dc<<<2i`seq -f%.f $[10**$1-1]|grep ^1*0*$|sort -r`f

Try it online!
The input n is passed in an argument.
Use seq to print all numbers with n or fewer digits. (These are base-10 numbers, so there are lots of extra numbers here. It's wasteful and time-consuming, but this is code golf!)
The call to grep keeps only those numbers that consist precisely of 1s followed by 0s.
Then use sort -r to sort these in reverse lexicographical order.
Finally, dc is set to base 2 input -- it pushes the sorted numbers on a stack and then prints the stack from top to bottom. (This prints the last item pushed first, etc., which is why I'm using sort -r instead of just sort.)
Corrected a bug: I had omitted the option -f%.f to seq, which is required for integer counts from 1000000 on.  (Thanks to @TobySpeight for pointing out that there was a problem.)

"Wasteful and time-consuming" ... and clever!  Thanks for this - it's a good reminder to wilfully ignore computational efficiency when golfing.  That's really hard when you spend the rest of your days writing fast and clear code...

Some values missing: dc<<<2i`seq $[10**7-1]|grep ^1*0*$|sort -r`f | wc - only reports 12 values.  I think you want grep ^1[01]*$ instead.

@TobySpeight Thanks -- there was a bug, which I've corrected. The problem wasn't with the regex; the issue was that seq required an option.   (I'm not sure why you were only getting 12 output values though -- even the incorrect version produced 21 output values intead of the correct 28. If you were running this on TIO, it may well have exceeded TIO's 1-minute time limit.)  I've tested this on both Linux and OS X now.

Actually, I misunderstood the question - the important word "consecutive" there somehow went straight past me!

Mathematica/Mathics, 69 bytes
{0,1}~Tuples~#~SortBy~Count@1/.n:{a=0...,1..,a}:>Print@Fold[#+##&,n]&

Try it online!

Python, 61 59 bytes
lambda n:[2**-~i-1<<j for i in range(n)for j in range(n-i)]

Try it online!

Japt, 11 bytes
o@o!²ãXÄ mx

Test it online!
Explanation
This pretty much uses @Dennis's approach:
o@ o!²  ãXÄ  mx
oX{o!p2 ãX+1 mx}
                  // Implicit: U = input integer
oX{            }  // Create the range [0...U) and map each item X by this function:
   o              //   Create the range [0...U)
    !p2           //     and map each item Z to 2.p(Z); that is, 2**Z.
                  //     (p2 would map each item Z to Z.p(2); ! reverses the arguments.)
        ãX+1      //   Get all overlapping slices of length X + 1.
             mx   //   Map each of these slices Z through Z.x(); that is, sum each slice.
                  // Implicit: output result of last expression

Perl 6, 38 bytes
->\n{map {|(2**$_-1 X+<0..n-$_)},1..n}

How it works
->\n{                                }  # A lambda with argument n.
                                 1..n   # Numbers from 1 to n.
     map {                     },       # Replace each one with a list:
            2**$_-1                     #   2 to that power minus 1,
                    X+<                 #   bit-shifted to the left by each element of
                       0..n-$_          #   the range from 0 to n minus the number.
          |(                  )         #   Slip the list into the outer list.

I.e. it constructs the numbers like this:
1 2 4 8 = (2^1)-1 bit-shifted to the left by 0 1 2 3 places
3 6 12  = (2^2)-1 bit-shifted to the left by 0 1 2   places
7 14    = (2^3)-1 bit-shifted to the left by 0 1     places
15      = (2^4)-1 bit-shifted to the left by 0       places     ← n rows
             ↑                                     ↑
             n                                     n-1

The code:

Perl 6, 44 bytes
->\n{map {|(2**$_-1,* *2...^*>2**n-1)},1..n}

This was my first approach before I thought of the (actually simpler) bit-shift solution above.
How it works
->\n{                                      }  # A lambda with argument n.
                                       1..n   # Numbers from 1 to n.
     map {                           }        # Replace each one with:
            2**$_-1                              # 2 to that power minus 1,
                   ,* *2                         # followed by the result of doubling it,
                        ...^                     # repeated until (but not including)
                            *>2**n-1             # it's larger than 2^n-1.
          |(                        )            # Slip the list into the outer list.

I.e. it constructs the numbers like this:
1 2 4 8 = (2^1)-1, times 2, times 2, times 2
3 6 12  = (2^2)-1, times 2, times 2
7 14    = (2^3)-1, times 2
15      = (2^4)-1                                ← n rows
             ↑                       ↑
             n                       as many columns as possible in
                                     each row without exceeding (2^n)-1

Haskell 59 46 Bytes
I started out with
f n=[0..n]>>= \b->take(n-b).iterate(*2).sum.map(2^)$[0..b]
from nimi's answer above gained the insight that sum.map(2^)$[0..x] can be condensed down to 2^x-1
Ending up with
e n=[1..n]>>= \x->map(\y->2^y*(2^x-1))[0..n-x]
[1..n] -- list with number of consecutive bits we want to cycle through`
>>= --roughly translated for each element in list on left pass it into the function on right and concatenate all results
\x -> -- lambda function declaration with one argument
map x y-- applies function x to all members of the list y
In our case x = (\y->2^y*(2^x-1)) -- another lambda function 2^y*(2^x-1)). This formula arises from multiplication by two adding a zero to right in binary(example 0001 to 0010). 2^x - 1 is the number of bits we are working with. so for 11 we have 2^0*3(i.e. dont shift at all) == 0011, then 2^1*3 = 0110 then 2^2*3 - 1100.
[0..n-x] Builds the list of how many times we can shift the bits. If we are working with a single 1 then looking at 0001 we want to shift 3 times (4-1). If we are working two 11 we want 4-2 and so on.

Python 3, 59 bytes
Note: this was made independently of ovs's and Dennis's solutions, even though it is very similar to both.
lambda n:[(2<<i)-1<<j for i in range(n)for j in range(n-i)]

How it works:
for i in range(n)for j in range(n-i)  # Iterate over number of ones, then number of places
                                      # shifted over. i = ones, j = shifts

(2<<i)                                # Create a one followed by i zeroes
      -1                              # Subtract one from above to get i ones.
        <<j                           # Shift j places.

Try it online!
Tips (both coding and cash) are always welcome!

PHP, 59 56 53 bytes
for(;$p>($k*=2)?:($p=1<<$argn)>$k=$i+=$i+1;)echo$k,_;

takes input from STDIN; run with -R.
breakdown
for(;$p>($k*=2)         // 3. inner loop: shift-0 $k while $k<$p (false in first iteration)
    ?:
    ($p=1<<$argvn)      // 1. init $p=2^N, outer loop:
    >$k=$i+=$i+1        // 2. shift-1 $i while $i<$p, init $k to new $i
;)
    echo$k,_;           // 4. print $k

You can use $argn Very good idea. After reading the question I have in my head a solution with over 200 Bytes

@JörgHülsermann Thanks for reminding me of STDIN. I just love merging loops.

Python 3, 91 bytes
a=int(input())
print(*[int('1'*-~b,2)<<c for b in range(a)for c in range(a-b)],sep=', ')

Full program, with comma+space separated output, as specified.
Explanation:
Star notation unpacks lists. So print(*[1,2,3]) is the same as print(1,2,3). Pass the int() constructor a string of consecutive '1's.
-~b evaluates to b+1, but you don't have to surround it with brackets when multiplying a string.
Bitshift the produced integer an increasing number of times. print() has the optional sep argument, specifying the string to put in between each item in an unpacked list.

You can just print the list. The output format isn't so strict.

J, 19 bytes
(0-.~&,>:+/\2&^)@i.

This uses the same method in @Dennis' solution.
Try it online!
Explanation
(0-.~&,>:+/\2&^)@i.  Input: integer n
                 i.  Range [0, 1, ..., n-1]
(              )@    Operate on that range
            2&^        Compute 2^x for each x in that range
       >:              Increment each in that range
           \           For each overlapping sublist of size (previous) in powers of 2
         +/              Reduce by addition
 0                     The constant 0
     &,                Flatten each
  -.~                  Remove zeroes

MATL, 19 18 bytes
1 byte saved thanks to @Luis
:q2w^XJfP"J@YC2&sv

Try it Online

QBIC, 37 bytes - imaginary bonus = still 37 bytes...
:[a|e=2^b-1┘while e<2^a┘?e┘e=e*2┘wend

Shame I haven't built while-wend into QBIC yet... Explanation:
:       Get N from the command line
[a|     For b = 1 to N; The sequence is reset N times
e=2^b-1 Set the first number of this sub-sequence (yields 1, 3, 7, 15 ...)
┘       Line-break - syntactic separation of commands because there's no command for WHILE yet.
while   Pure QBasic code - lower-case is not (really) interpreted by QBIC
e<2^a   Continue as long as we don't exceed the maximum value
┘?e     Print the number in the sequence
┘e=e*2  Double the number
┘wend   And loop as long as we're not exceeding maximum, reset the sequence otherwise.
        FOR loop auto-closed by QBIC

EDIT: QBIC now has support for WHILE:
:[a|e=2^b-1≈e<2^a|?e┘e=e*2

This is only 26 bytes! Here's the WHILE:
≈e<2^a|          ≈ = WHILE, and the TRUE condition is everything up to the |
       ...       Loop code goes here
          ]      Close construct: adds a WEND instruction
                 In the program above, this is done implicitly because of EOF.

Java 7, 108 bytes
static void x(int i){int a=0,t=1<<i,b;while((a=(a<<1)+1)<t){b=a;do System.out.println(b);while((b<<=1)<t);}}

Doubles the initial value as long as the result is smaller than 2^n. Afterwards, updates the initial value to be (initial_value * 2) + 1 and starts again from there until it eventually reaches (2^n)-1.
e.g. for n=4:
0001 -> init
0010
0100
1000
return, double init and add one
0011 -> init
0110
1100
return, double init and add one
0111 -> init
1110
return, double init and add one
1111 -> init
done

Try it online!

Ruby, 50 bytes
->r{1.upto(r){|x|p a=2**x-1;p a while(a*=2)<2**r}}

I tried some "clever" approaches, but this seems to be the shortest (literally follow the instructions)
Explanation:
Each iteration starts with 2^n-1 and multiplies by 2 until the upper limit is reached. Nothing fancy, just basic math.

R, 69 48 46 bytes
n=scan();for(i in 1:n)print((2^i-1)*2^(i:n-i))

Each decimal number corresponding to i in 1..n ones in binary system is multiplied by 2^(0..n-i), i.e first n-i+1 powers of two (1, 2, 4, ...).
Try it online!

Stax, 9 bytes
übg▓}╥é►╪

Run and debug online!
Explanation

Imaginary bonus if someone does this without any form of base conversion (using plain old maths).

Well, there are no base conversion here.
Uses the unpacked version (10 bytes) to explain.
m|2vx_-DQH
m             For input=`n`, loop over `1..n`
 |2v          Power of two minus one
    x_-D      Do `n-j` times, where `j` is the current 1-based loop index
        Q     Output the current value
         H    And double it

Batch, 92 - 0 = 92 bytes
@for /l %%i in (1,1,%1)do @for /l %%j in (%%i,1,%1)do @cmd/cset/a"(1<<%%i)-1<<%%j-%%i"&echo(

Subtracting 0 for @StewieGriffin's imaginary bonus.

C, 69 bytes
New way:
m;s;f(n){for(m=1;m<<=1<=1<<n;)for(s=m-1;s<1<<n;s*=2)printf("%d ",s);}

previous 72 bytes solution:
i;s;f(n){for(i=1;i<=n;++i){for(s=(1<<i)-1;s<1<<n;s*=2)printf("%d ",s);}}

Perl 5, 51 bytes
map{$_=2**$_-1;do{say}while($_*=2)<2**$l}1..($l=<>)

Try it online!


text:
Twisting Sentences
Rules
The program should receive a string/array of words as input. For each word in the string/array, it will reconstruct the word by taking characters in alternating fashion from the front and back of the word.
12345 678 9 -> 15243 687 9.
It will then rearrange the words in an alternating fashion between the earliest and the latest occurring word in the string.
15243 687 9 -> 15243 9 687
Finally, it will reconstruct the string by placing the spaces, tabs and newlines at the indexes where they were initially located before outputting the result.
12345 678 9-> 15243 687 9 -> 15243 9 687 -> 15243 968 7
Output should be the same datatype as the input.
Standard Loopholes are forbidden
Examples

Input:
The quick brown fox jumps over the lazy dog.
Output:
Teh d.ogq kucil yaz bnrwo tehf xoo rvej supm
Input:
The quick brown fox jumps
over the lazy dog.
Output:
Teh d.ogq kucil yaz bnrwo
tehf xoo rvej supm
Input:
Aflack
Output:
Akfcla

This is code-golf so shortest code wins

This feels like a duplicate. I swear I've seen this before.

So only tab, space and newline characters are not considered part of a word?

@JonathanAllan that is correct

Can we assume ASCII? or Unicode?

@MayorMonty You can assume the characters are whichever form makes it easier for you so long as it treats spaces properly.

Jelly, 15 14  8 bytes
A whopping 6 byte save from Dennis (by moving the flatten and mould inside link 1 there is no need to split into two and head, and a flatten is there already so they become one!)
żṚFṁ
Ç€Ç

(from the two lines: żṚFœs2Ḣ, and Ç€ÇFṁ⁸)
Try it online!
Takes an array of words and returns an array of new words. (The Footer at TIO calls this and joins the array with spaces so it prints out nicely.)
Note - handling a single string, splitting on tabs spaces and newlines, then reassembling was actually proving rather tricky; once I saw that a list of words was an option things got a lot easier!
How?
Ç€Ç - Main link: list of words
Ç€  - call the last link (1) as a monad for €ach word
  Ç - call the last link (1) as a monad for the result

żṚFṁ - Link 1: Do a twist: list (here, a list of words or characters)
                            e.g. input = [A,B,C,D,E,F,G]
ż    - zip the list with                 [A,    B,    C,    D,    E,    F,    G]
 Ṛ   - the reverse of the list             [G,    F,    E,    D,    C,    B,    A]
                                        [[A,G],[B,F],[C,E],[D,D],[E,C],[F,B],[G,A]]
  F  - flatten into a single list        [A,G,  B,F,  C,E,  D,D,  E,C,  F,B,  G,A]
                                         [A,G,B,F,C,E,D,D,E,C,F,B,G,A]
   ṁ - mould like the input list         [A,G,B,F,C,E,D]

This should work. Try it online!

Sweet save; too easy to forget that manoeuvre!

JavaScript (ES6), 89 bytes
Takes and outputs an array of words.
a=>a.map(w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(a.map(F)).slice(p,p+=w.length),p=0)

Test

let f =

a=>a.map(w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(a.map(F)).slice(p,p+=w.length),p=0)

console.log(
  JSON.stringify(
    f(["The","quick","brown","fox","jumps","over","the","lazy","dog."])
  )
);

String version, 112 bytes
Takes and outputs a string.
s=>s.replace(/\S+/g,w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(s.split(/\s/).map(F)).slice(p,p+=w.length),p=0)

Test

let f =

s=>s.replace(/\S+/g,w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(s.split(/\s/).map(F)).slice(p,p+=w.length),p=0)

console.log(f(`The quick brown fox jumps over the lazy dog.`))

console.log(f(`The quick brown fox jumps
over the lazy dog.`))

console.log(f(`Aflack`))

Perl, 77 bytes
74 bytes of code + 3 bytes for -0pa flags.
map{s/.\K/chop/ge,s/../chop/reg}@F;s/\S/($r||=$F[$i++].pop@F)=~s%.%%,$&/ge

Try it online!
Saved 8 bytes thanks to an old @Ton Hospel's post where I "stole" s/../chop/reg. (I previously had $c=y///c/2,s/.{$c}$//)

Perl 6, 84 bytes
{my &t={(|(.shift,.pop)xx*)[^$_]}
map({|t [.comb]},t [$_]).rotor($_».chars)».join}

Inputs and outputs a list of words.
How it works
Inside the lambda, I defined another lambda to perform the "taking characters in alternating fashion from the front and back" twisting:
my &t={                        }   # Lambda, assigned to a variable.
          .shift,.pop              # Remove an element from the front an back,
                      xx*          # an infinite number of times,
        |(           )             # and make sure this infinite list is flattened.
                          [^$_]    # Take as many elements as the input had elements.

This works because the xx operator is more like a macro than a function, in that it provides magic lazy evaluation.
Then in the main lambda:
                   [$_]                          # Create a fresh array from the input,
                 t                               # and twist it (destructively).
map({          },                                # For each element (i.e. word):
      t [.comb]                                  #   Split it into characters and twist them,
     |                                           #   and slip them into the outer list.
                        .rotor($_».chars)        # Partition this flat list of characters,
                               $_».chars         # using the original word lengths.
                                         ».join  # Turn each sub-list into a word.

Perl 6, 87 bytes
{my &t={(|(.shift,.pop)xx*)[^$_]}
my @a=map {|t [.comb]},t [.words];S:g/\S/{@a.shift}/}

This is a variation of the above, which inputs and outputs a string – preserving different whitespace characters.

Haskell, 115 95 93 98 95 bytes
f(a:b)=a:f(reverse b)
f e=e
a!(y:z)|elem y" \t\n"=y:a!z|b:c<-a=b:c!z
a!z=z
(!)=<<(f=<<).f.words

Call with (!)=<<(f=<<).f.words $ "some string". Try it online!
Thanks to @nimi for pointing out that I misread the challenge earlier.
The function f performs the twisting on a list, so it can be used on strings (list of chars) and a list of strings.
a!b inserts the whitespace of string b into string a.
(!)=<<(f=<<).f.words is equivalent to \s0 -> (concatMap f . f . words $ s0) ! s0:
            s0 = "The quick brown fox jumps\nover the lazy dog."
      words s0 = ["The","quick","brown","fox","jumps","over","the","lazy","dog."] = s1
          f s1 = ["The","dog.","quick","lazy","brown","the","fox","over","jumps"] = s2
concatMap f s2 = "Tehd.ogqkucilyazbnrwotehfxoorvejsupm"                           = s3
       s3 ! s0 = "Teh d.ogq kucil yaz bnrwo\ntehf xoo rvej supm"

Husk, 14 bytes
UΣSze↔mȯUΣSze↔

Try it online!
This doesn't work with a reusable function since a function can only support one type of arguments.


text:
Tips for golfing in TikZ
TikZ is a Latex package used for drawing precise images in Latex documents.  It has a massive specification and a boatload of features that may be useful for graphical-output style questions.
What tips do people have for golfing in TikZ?  As always, tips should be specific to to TikZ (e.g. "Remove comments" is not an answer), and stick to a single tip per answer.

Does anyone golf in Tikz?

@Pavel I do.

Shouldn't this be a question for meta ?

@WheatWizard  It seems like a question about "how to approach answering a question" , rather than a programming puzzle itself. I see there's a tips tag, so I assume it's on-topic on the main site. Still learning the ropes on this site, so questions about how to approach answering/reducing answers seems  more suitable for meta site rather than main one.

@Serg There are a good deal of [tag:tips] questions of similar content on the main site.  These are generally considered to be on-topic.

For those interested, there is a tikz/pgf manual (its where I found the information for my answers).
Version 3.0.1a,
Version 2.10

Do you think this question is worth generalizing/editing to "Tips for golfing in TeX/LaTeX", or should I create a new question? Things like \def are not specific to TikZ, and I have some more answers I'd like to add (but none are TikZ-related).

@ShreevatsaR I think perhaps a new question should be made for TeX/LaTeX, all of the tips here are currently specific to Tikz, and I can see some benefit in keeping them separate.

@WheatWizard Ok makes sense; I've created a new question here.

Use \def
\def is an incredibly powerful tool when it comes to golfing.  \def allows you to assign something to a variable.
This can be used simply with the to save a number you may use a bunch of times for instance
\def\x{1456}

Will define 1456 as \x for future use much like saving a variable might in a programming language.
However \def is much more powerful than that, because \def doesn't define a variable it defines a snippet of code to be substituted into the program whenever it is called.
For example say you want to draw some rectangles using \draw  you might write the following code:
\draw(0,0)rectangle(3,4)rectangle(8,0);\draw(2,2)rectangle(3,3);

Using \def this could be written as:
\def\x{)rectangle(}\draw(0,0\x3,4\x8,0);\draw(2,2\x3,3);

This is brilliant in golfing point of view but also very useful to more deeply understand these important commands...you know when they ask you "what is the difference between \def and \newcommand"...

Use \tikz instead of the tikzpicture environment
Instead of creating a tikzpicture environment (36 bytes) you can use the \tikz command (7 bytes)
Global options can be set in square brackets in using the tikz command as such \tikz[options...]{...}. If the tikz code is one line long the curly braces can be omitted saving an additional two bytes.
Example:
Both of the following programs output the image at the bottom
\documentclass{standalone}\input tikz\begin{document}\tikz{\draw[thick,rounded corners=8pt](0,0)--(0,2)--(1,3.25)--(2,2)--(2,0)--(0,2)--(2,2)--(0,0)--(2,0);\draw(-1.5,0)--(0,1.5);}\end{document}

\documentclass{standalone}\input tikz\begin{document}\begin{tikzpicture}\draw[thick,rounded corners=8pt](0,0)--(0,2)--(1,3.25)--(2,2)--(2,0)--(0,2)--(2,2)--(0,0)--(2,0);\draw(-1.5,0)--(0,1.5);\end{tikzpicture}\end{document}

Credit to WheatWizard for figuring the multiline use of \tikz

Use \documentclass[tikz]{standalone}
By chance I found the following in the manual of the standalone package:

For pictures drawn with TikZ a dedicated tikz option is provided which
  loads the tikz package and also configures the tikzpicture environment
  to create a single cropped page.

Thus, instead of
\documentclass{standalone}\input tikz\begin{document} ...

one can write
\documentclass[tikz]{standalone}\begin{document} ...

to save 5 bytes.

You can sometimes refrain from using co-ordinate (0,0) completely.
That's an easy one.
Here's a more intricate one:
(,) is the same as (1,1).
Found out that one rather by accident.Here's a minimal example:
\documentclass[tikz,border=9]{standalone}\def~{document}\begin~\tikz{\draw grid(,);}\end~

Output: