[Question]
  [
# Problem
Starting from `n=2` dice:
* Roll `n` dice, with each number 1 to 6 equally likely on each die.
* Check if their sum equals the most probable sum for `n` dice, that is `3.5*n`.
	+ If they're equal, terminate.
	+ Otherwise, print `n`, and repeat from the start with `n+2` dice
Your code doesn't have to do this procedure exactly, but should give random output probabilistically equivalent to it, based on [our definition of randomness](https://codegolf.meta.stackexchange.com/a/1325/20260).
Your program should output all of the numbers on their own line; for example, if the program got up to 8 dice and rolled the most probable number with 8 dice, the output would be:
```
2
4
6
```
# Example Run
On 2 dice, `7` is the most probable sum. Let's say the numbers rolled were `2` and `3`. Then, you would print `2`.
On 4 dice, `14` is the most probable sum. Let's say the numbers rolled were `3`, `4`, `2`, and `5`. Then, the sum is `14`, so the program would terminate here.
The final output in this case is `"2"`. 
# Rules
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution in bytes wins
* [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* The [meta definition of randomness](https://codegolf.meta.stackexchange.com/a/1325/42649) applies
* You may use functions as well as programs
  
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
from random import*
n=2
while eval("+randrange(6)-2.5"*n):print n;n+=2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VoceXZGnGVZ2TmpCqkliXmaChpg@SBOD1Vw0xT10jPVEkrT9OqoCgzr0QhzzpP2xZozte8fN3kxOSMVAA "Python 2 – Try It Online")
The trick is to compute the sum by `eval`ing a string the looks like
```
'+randrange(6)-2.5+randrange(6)-2.5'
```
with `n` copies of the expression concatenated. The `randrange(6)` outputs a random number from `[0,1,2,3,4,5]`, which is shifted down by `2.5` to have average of `0`. When the sum if `0`, the `while` condition fails and the loop terminates.
An alternative using `map` was 4 bytes longer:
```
from random import*
n=2
while sum(map(randrange,[6]*n))-2.5*n:print n;n+=2
```
I've found a bunch of equal-length expressions for a die shifted to mean zero, but none shorter
```
randrange(6)-2.5
randint(0,5)-2.5
randrange(6)*2-5
uniform(-3,3)//1
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
`@E6y&Yrs@7*-
```
[Try it online!](https://tio.run/##y00syfn/P8HB1axSLbKo2MFcS/f//695@brJickZqQA "MATL – Try It Online")
### Explanation
```
`       % Do...while top of the stack is truthy
  @E    %   Push 2*k, where k is the iteration index starting at 1
  6     %   Push 6
  y     %   Duplicate 2*k onto the top of the stack
  &Yr   %   Array of 2*k integers distributed uniformly in {1, 2, ..., 6}
  s     %   Sum
  @7*   %   Push 7*k
  -     %   Subtract
        % End (implicit). If the top of the stack is non-zero, the loop
        % proceeds with the next iteration. Else the loop is exited.
        % Display stack (implicit)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-5 bytes with help from Leaky Nun (moving from count up to recursion)
```
‘‘6ṗX_3.L⁶S?Ṅß
```
A full program printing the results separated by newlines (an extra space and newline are also printed, and the program errors at the end).
**[Try it online!](https://tio.run/##y0rNyan8//9RwwwgMnu4c3pEvLGez6PGbcH2D3e2HJ7////XvHzd5MTkjFQA "Jelly – Try It Online")** - any time 6 dice are surpassed TIO kills this due to memory usage, but it works in principle - it also takes ~40s to do so.
A more friendly 15 byte version that does not take so long or require so much memory is available **[here](https://tio.run/##y0rNyan8//9RwwwgMnu4qzviUdOaeGM9n0eN24LtH@5sOTz///@vefm6yYnJGakA "Jelly – Try It Online")**.
### How?
Recursively rolls 2 more dice until the sum of the faces each reduced by 3.5 is zero, printing the number of dice as it goes, when the zero is reached it attempts to use a space character causing a type error.
```
‘‘6ṗX_3.L⁶S?Ṅß - Main link: no arguments (implicit left=zero)
‘              - increment (initial zero or the previous result)
 ‘             - increment  (= # of dice to roll, n)
  6            - literal 6
   ṗ           - Cartesian power - all possible rolls of n 6-sided dice with faces 1-6
    X          - pick one of them
      3.       - literal 3.5
     _         - subtract 3.5 from each of the roll results
           ?   - if:
          S    -          sum the adjusted roll results (will be 0 for most common)
        L      - ...then: length (number of dice that were rolled)
         ⁶     - ...else: literal ' ' (causes error when incremented in next step)
            Ṅ  - print that plus a newline
             ß - call this link with the same arity (as a monad with the result)
```
[Answer]
# TI-BASIC, 28 bytes
```
2→N
While mean(randInt(1,6,N)-3.5
Disp N
N+2→N
End
```
**Explanation**
* `randInt(1,6,N)` generates a list of N random numbers from 1 to 6
* `mean(randInt(1,6,N)-3.5` gets the average of the rolls shifted down by 3.5
* `While` continues until the average expression equals zero (the most probable sum)
[Answer]
# [R](https://www.r-project.org/), 49 bytes
```
n=2
while(sum(sample(6,n,T)-3.5)){print(n)
n=n+2}
```
`sample(6,n,T)` generates `n` (pseudo)random samples from the range `1:6` with replacement. Subtracting 3.5 from each element yields a result whose `sum` is 0 (falsey) if and only if it's the most common value.
[Try it online!](https://tio.run/##K/r/P8/WiKs8IzMnVaO4NFejODG3AMg008nTCdHUNdYz1dSsLijKzCvRyNPkyrPN0zaq/f8fAA "R – Try It Online")
Skips the odd dice rolls.
[Answer]
# Java 8, ~~123~~ ~~149~~ ~~113~~ 108 bytes
```
()->{for(int n=0,s=1,i;s!=n*7;){for(i=s=++n*2;i-->0;s+=Math.random()*6);if(s!=n*7)System.out.println(n*2);}}
```
Or **107 bytes** if we use [an `Object null` as unused parameter](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding) instead.
+26 bytes for a bug-fix, correctly pointed out by *@Jules* in the comments.  
-41 bytes thanks to *@OliverGrégoire*'s great thinking!
**Explanation:**
[Try it here.](https://tio.run/##PY6xDoIwEIZ3n@LcWrBEHXRo6hvA4mgczlK0CFdCq4kxPLYzVjEul/y5@@7/aryjcJ2huryOukHvIUdLzxmApWD6CrWB4hMB7s6WoBmXMQ2zOHzAYDUUQKBgZFzsnpXrWQSB1HLh1WphpZ8rSraSTyvlVZpSspZWiN1S@lTlGC5Zj1S6lvFkw6Wt2MTw/cMH02buFrKuj18bYhHlchhG@envbqcm9v80vnptlGf7EK/PhyMgn8wp@2sP44uc0Kgv5g0)
```
()->{                           // Method without parameter nor return-type
  for(int n=0,                  //  Amount of dice
          s=1,                  //  Sum
          i;                    //  Index
      s!=n*7;){                 //  Loop (1) as long as the sum doesn't equal `n`*7,
                                //  because we roll the dice per two, and 3.5*2=7
    for(i=s=++n*2;              //   Reset both the index and sum to `n`*2,
                                //   so we can use random 0-5, instead of 1-6
                                //   and we won't have to use `+1` at `Math.random()*6`
        i-->0;                  //   Inner loop (2) over the amount of dice
        s+=Math.random()*6      //    And increase the sum with their random results
    );                          //   End of inner loop (2)
    if(s!=n*7)                  //   If the sum doesn't equal `n`*7
      System.out.println(n*2);  //    Print the amount of dice for this iteration 
  }                             //  End of loop (1)
}                               // End of method
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 20 bytes
-2 Bytes thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)
```
[YF6L.RO}7Y*;ïQ#Y=ÌV
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/OtLNzEcvyL/WPFLL@vD6QOVI28M9Yf//f83L101OTM5IBQA "05AB1E – Try It Online")
### Explanation
```
[YF6L.RO}7Y*;ïQ#Y=ÌV
[                    # Infinite loop start
 YF     }            # Y times... (Y defaults to 2)
   6L.R               # Push a random number between 1 and 6 (why does this have to be so looooong ._.)
       O              # Sum
         7Y*;ï       # Push 3.5 * Y as an int
              Q      # Is it equal to 3.5 * Y?
               #     # If so: Quit
                Y    # Push Y
                 =   # Print without popping
                  ÌV # Set Y to Y + 2
```
[Answer]
# R, ~~48~~ ~~44~~ 42 bytes
A 5-byte improvement on [Giuseppe's answer](https://codegolf.stackexchange.com/a/126090/59052).
```
while(sum(sample(6,F<-F+2,1)-3.5))print(F)
```
This (ab)uses the fact that `F` is a variable by default assigned to `FALSE` which coerces to `0` and can then be incremented, saving us the need to initialize a counter variable.
[Answer]
# [PHP](https://php.net/), 75 bytes
```
for($d=2;(++$i*7/2-$r+=rand(1,6))||$i<$d;)$i%$d?:$d+=1+print"$d
".$r=$i="";
```
[Try it online!](https://tio.run/##DcQxDoMwDAXQvceIfqWkhlYwUIlgcRaEi/ASIosx1@4ceMPLe67TnO@3wzyE@@iJoK/vp29hxLYk8V0zhFAKdILEAH1C5hFC3FE2TaeDPNwbxlB2Ltb6T0e7Luv@uwA "PHP – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 41 bytes
```
0{2+.n\.[{6rand.+5-}*]{+}*!!*.}{}while;;;
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/36DaSFsvL0YvutqsKDEvRU/bVLdWK7Zau1ZLUVFLr7a6tjwjMyfV2tr6//@vefm6yYnJGakA "GolfScript – Try It Online")
[Answer]
# Mathematica, 47 bytes
```
For[n=1,Tr@RandomInteger[5,2n++]!=5n,Print[2n]]
```
*-5 bytes from LLlAMnYP*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
[N·ÌD6Lã.R7;-O_#,
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2u/Q9sM9LmY@hxfrBZlb6/rHK@v8//81L183OTE5IxUA "05AB1E – Try It Online")
**Explanation**
```
[                   # loop over N in 0...
 N·Ì                # push N*2+2
    D               # duplicate
     6L             # push range [1 ... 6]
       ã            # cartesian product (combinations of N*2+2 elements in range)
        .R          # pick one at random
          7;-       # subtract 3.5 from each dice roll
             O_#    # if sum == 0 exit loop
                ,   # otherwise print the copy of N*2+2
```
[Answer]
## Batch, 109 bytes
```
@set/an=%1+2,s=n*5/2
@for /l %%i in (1,1,%n%)do @call set/as-=%%random%%%%%%6
@if %s% neq 0 echo %n%&%0 %n%
```
Rather annoyingly, `random` is a magic environment variable, so it only gets replaced with a random value during environment expansion, which normally happens before the for loop starts. `call` makes it happen each time through the loop, but then you need to double the `%` signs to prevent the expansion from happening before the loop. The fun starts because we want to modulo the result by 6, which requires a real `%` sign, which now has to be doubled twice. The result is six consecutive `%`s.
[Answer]
# JavaScript (ES2015), 75 78 bytes
```
f=(n=2)=>[...Array(n)].reduce(a=>a+Math.random()*6|0,n)==3.5*n?'':n+`
`+f(n+2)
```
Outputs a string of results separated by newlines
Edit: saved a byte thanks to Shaggy, added 4 bytes to start function at 2
**Explanation**
```
f=n=>
  [...Array(n)]                // Array of size n
    .reduce(                   // Combine each item
      a=>a+Math.random()*6|0,  // Add a random roll between 0 and 5 for each item
    n)                         // Start at n to correct rolls to between 1 and 6
    ==3.5*n                    // Compare total to most probable roll total
  ? ''                         // If true, end
  : n+'\n'+f(n+2)              // Otherwise, output n and continue
```
```
f=(n=2)=>[...Array(n)].reduce(a=>a+Math.random()*6|0,n)==3.5*n?'':n+`
`+f(n+2)
let roll = _ => document.getElementById('rolls').innerHTML = f();
document.getElementById('roll-button').onclick = roll;
roll();
```
```
<button id="roll-button">Roll</button>
<pre id="rolls"></pre>
```
[Answer]
# php - 89 Characters
```
$r=0;$n=2;while($r!=$n*3.5){$r=$i=0;while($i<$n){$r+=rand(1,6);$i++;}print $n."
";$n+=2;}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~ ~~80~~ ~~79~~ ~~77~~ ~~75~~ ~~80~~ ~~78~~ 76 bytes
```
i;f(s,j){for(;s;s?printf("%d\n",i):0)for(j=i+=2,s=i*7/2;j--;)s-=1+rand()%6;}
```
[Try it online!](https://tio.run/##LYlBCsIwEADveYUUCrs2wdqDBZfgR7yEtNENNJVsb6XP9hy1OKdhxpuH96UwBRAdcQ1zBhKS2ytzWgJU9XBPlWa8tvh70XJjOy2Wj/2po2gMoRh7brJLA2B9oa1MjhOgWtXhi@xj4WmEFpH2FuAvaivvNBvv/HP8AA "C (gcc) – Try It Online")
[Answer]
# Haskell ~~133~~ 132 bytes
```
import System.Random;import Control.Monad
s k=do n<-replicateM k$randomRIO(1,6);if sum n==7*div k 2 then pure()else do print k;s(k+2)
```
Credit to @Laikoni for the suggestions in the comments below.
[Answer]
# **Octave 55 bytes**
```
n=2;
while mean(randi(6,n,1))-3.5!=0
n
n=n+2;
end
```
Inspired by Andrewarchi's answer. If someone has any pointers to even shorten it, they are welcome. 
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
K2WnsmhO6K*K3.5K=+K2
```
[Try it online!](https://tio.run/##K6gsyfj/39soPK84N8PfzFvL21jP1NtW29vo////X/PydZMTkzNSAQ "Pyth – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 40 bytes
```
{[1,r|g=g+_r1,6|]~g=r*3.5|_X\g=0?r┘r=r+2
```
Thispretty much literally does what the challenge asks for; seems the shortest way to get the distribution right.
## Explanation
```
{          DO infinitely
[1,r|      FOR a=1, a<=r (at start, r == 2), a++
g=g+       Add to g (0 at start)
  _r1,6|   a random number between 1 and 6 incl.
]          NEXT
~g=r*3.5   IF the result of all dice rolls equals the expected value
|_X        THEN quit
\g=0       ELSE, reset the dice total
?r┘        PRINT the number of dice used
r=r+2      and add 2 dice.
           END IF and LOOP are courtiously provided by QBIC at EOF.
```
[Answer]
# [Rexx (Regina)](http://www.rexx.org/), 78 bytes
```
x=2
do forever
  t=0
  do x
    t=t+random(6)
  end
  if(t=x*3.5)then
    exit
  say x
  x=x+2
end
```
[Try it online!](https://tio.run/##Fcs9CoAwDEDhPafo6A@KKLrlMKWNtIMt1CDx4M6xHR98r5CIquAKPpszF3qoAOPSUsAYRh6LTT5f3dEDJQ/x7Bhl2Oa950CpGpLIcNu3DoIyro2pfilPzrpAPw "Rexx (Regina) – Try It Online")
[Answer]
# JavaScript (ES6) - 69 Characters
```
r=n=>n?r(n-1)+(Math.random()*6|0)-2.5:0;f=(n=2)=>r(n)?n+`
`+f(n+2):""
console.log(f())
```
**Explanation**:
```
r=n=>                                     # Roll n dice
     n?                                   # If there is a dice left to roll
       r(n-1)                             #   Roll n-1 dice
             +(Math.random()*6|0)         #   Add a random number from 0 .. 5
                                 -2.5     #   Subtract 2.5 so sum of average is 0
                                     :0   # Else total is 0
```
and:
```
f=(n=2)=>                                 # Start with n = 2
         r(n)                             # Roll n dice
             ?n+"\n"+f(n+2)               # If non-zero then concatenate n, newline and
                                          #    result for n+2 dice
                           :""            # If zero (average) terminate.
```
[Answer]
# [Calc2](https://github.com/hstde/Calc2) 0.7, ~~119~~ ~~118~~ 111 bytes
```
using"runtime";for(n=2,d=0;d!=3.5*n;Console.WriteLine(n),n+=2)for(i=d=0;i++<n;)d+=Math.Int(Random().Next(1,7));
```
ungolfed:
```
using "runtime";
var d = 0;
var r = Random();
for(var n = 2; d != 3.5 * n; Console.WriteLine(n), n += 2)
{
    d = 0;
    for(var i = 0; i < n; i++)
        d += Math.Int(r.Next(1,7));
}
```
I could do without the Math.Int() but unfortunately in 0.7 the Random().Next() functions have a bug where they all return doubles instead of ints. It has been fixed but only after this question was posted.
I'm not gonna win anything, but hey, nice proof of concept.
Edit:
* removed unnecessary space between using and "runtime" (-1 byte)
Edit2:
* removed var r and create a new Random where it's needed (-4 byte)
* changed i=0,d=0 to i=d=0 (-2 byte)
* incremented i after check (-1 byte)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 52 bytes
```
s=x=2;(s=0;p x.times{s+=rand(6)-2.5};x+=2)while s!=0
```
### Explanation
```
s=x=2;                                                # sum=2, x=2
      (                                  )while s!=0  # while sum != 0:
       s=0;                                           #  reset the sum
           p                                          #  print
             x.times{              };                 #  repeat x times:
                     s+=                              #   Add to sum:
                        rand(6)                       #    random int in 0..5
                               -2.5                   #    subtract average
                                                      #  (implicitly return x for printing)
                                     x+=2             #  Increment x by 2
```
[Try it online!](https://tio.run/##KypNqvz/v9i2wtbIWqPY1sC6QKFCryQzN7W4uljbtigxL0XDTFPXSM@01rpC29ZIszwjMydVoVjR1uD//695@brJickZqQA "Ruby – Try It Online")
[Answer]
# Javascript, 87 chars
```
for(n=2;eval('+'.repeat(n).replace(/./g,x=>x+(Math.random()*6|0)))!=2.5*n;n+=2)alert(n)
```
Test with `console.log` instead of `alert`:
```
for(n=2;eval('+'.repeat(n).replace(/./g,x=>x+(Math.random()*6|0)))!=2.5*n;n+=2)console.log(n)
console.log('Done')
```
[Answer]
## lua, 102 bytes
```
function r(n,t) for d=1,n do t=t+math.random(1,6)end return t==n*3.5 or print(n)or r(n+2,0)end r(2,0)
```
Or the more readable version
```
function r(n,t) --recursive function does its magic, t is given to safe usage bytes(no local)
    for d=1,n do --roll n dice and count them up to the total (t)
         t =t+math.random(1,6)
    end 
    return t==n*3.5 or --check if t==n*3.5. If it is then it ends
           print(n) or --t != n*3.5 thus print n. print returns nil
           r(n+2,0) --both the check and the return value from print are false thus r gets executed.
end 
r(2,0) --start the process
```
A more cheaty version for 96 bytes
```
function r(n,t,m)t=t+m(1,6)+m(1,6)return t==n*3.5 or print(n)or r(n+2,t,m)end r(2,0,math.random)
```
This pretty much works the same as the first but reuses the rolls from earlier calls. Because of this I can remove the for loop.
Both are tested in lua 5.2
[Answer]
# [Perl 6](http://perl6.org/), 48 bytes
```
.say for 2,*+2...^{3.5*$_==sum (1..6).pick xx$_}
```
]