[Question]
  [
Define the function *f(n)* for a positive integer *n* as follows:
* *n / 2*, if *n* is even
* *3 \* n + 1*, if *n* is odd
If you repeatedly apply this function to any *n* greater than 0, the result always seems to converge to 1 (though nobody's been able to prove that yet). This property is known as the [Collatz Conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture).
Define an integer's *stopping time* as the number of times you have to pass it through the Collatz function *f* before it reaches 1. Here are the stopping times of the first 15 integers:
```
1  0
2  1
3  7
4  2
5  5
6  8
7  16
8  3
9  19
10 6
11 14
12 9
13 9
14 17
15 17
```
Let's call any set of numbers with the same stopping time *Collatz cousins*. For example, 5 and 32 are Collatz cousins, with a stopping time of 5.
Your task: write a program or function that takes a nonnegative integer and generates the set of Collatz cousins whose stopping time is equal to that integer.
## Input
A nonnegative integer S, given via STDIN, ARGV, or function argument.
## Output
A list of all numbers whose stopping time is S, **sorted** in **ascending** order. The list may be output by your program, or returned or output by your function. Output format is flexible: space-separated, newline-separated, or any standard list format of your language is fine, as long as the numbers are easily distinguishable from one another.
## Requirements
Your submission must give correct results for any S ≤ 30. It should finish in seconds or minutes, not hours or days.
## Examples
```
0  -> 1
1  -> 2
5  -> 5, 32
9  -> 12, 13, 80, 84, 85, 512
15 -> 22, 23, 136, 138, 140, 141, 150, 151, 768, 832, 848, 852, 853, 904, 906, 908, 909, 5120, 5376, 5440, 5456, 5460, 5461, 32768
```
Here is a Gist of the output for [S = 30](https://gist.github.com/dloscutoff/2cea4ebd0cea81f0cf90).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest program in bytes wins. Good luck!
  
[Answer]
# Mathematica, ~~98~~ ~~92~~ 89 bytes
This solution solves `S = 30` immediately:
```
(p={0};l={1};Do[l=Complement[##&@@{2#,Mod[a=#-1,2]#~Mod~3~Mod~2a/3}&/@l,p=p⋃l],{#}];l)&
```
This is an unnamed function taking `S` as its only parameter and returning a list of the Collatz cousins.
The algorithm is a simple breadth-first search. The Collatz cousins for a given `S` are all the integers that can be reached from the Collatz cousins for `S-1` via `2*n` or odd numbers that can be reached via `(n-1)/3`. We also need to ensure that we only produce those integers which were reached for the *first time* after `S` steps, so we keep track of all previous cousins in `p` and remove those from the result. Since we're doing that anyway, we can save a few bytes by computing the steps from *all* previous cousins (not just those from `S-1`) to save a few bytes (that makes it slightly slower, but not noticeably for the required `S`).
Here is a slightly more readable version:
```
(
  p = {0};
  l = {1};
  Do[
    l = Complement[
      ## & @@ {2 #, Mod[a = # - 1, 2] #~Mod~3~Mod~2 a/3} & /@ l,
      p = p ⋃ l
    ]~Cases~_Integer,
    {#}
  ];
  l
) &
```
[Answer]
# Pyth, ~~26~~ ~~24~~ 21 bytes
```
Su+yMG-/R3fq4%T6G1Q]1
```
This code runs instantly for `S=30`. Try it out yourself: [Demonstration](https://pyth.herokuapp.com/?code=Su-%2ByMG%2FR3fq4%25T6G1Q%5D1&input=30&debug=0)
Thanks to @isaacg for saving 5 bytes. 
### Explanation
My code starts with `1` and undos the Collatz function. It maps all numbers `d` of the `S-1` step to `2*d` and `(d-1)/3`. The last one in not always valid though. 
```
                        implicit: Q = input number
                   ]1   start with G = [1]
 u                Q     apply the following function Q-times to G:
                          update G by
   yMG                      each number in G doubled
  +                       +
          fq4%T6G           filter G for numbers T, which satisfy 4==T%6
       /R3                  and divide them by 3
      -          1          and remove 1, if it is in the list
                            (to avoid jumping from 4 to 1)
S                       sort the result and print
```
[Answer]
# Python 2, ~~86~~ ~~83~~ ~~75~~ ~~73~~ 71 bytes
```
f=lambda n,k=1:sorted([k][n:]or(k>4==k%6and f(n-1,k/3)or[])+f(n-1,k*2))
```
Call like `f(30)`. `n = 30` is pretty much instant.
*(Thanks to @DLosc for the idea of recursing by `k` being a number rather than a list of cousins, and a few bytes. Thank to @isaacg for dropping `~-`.)*
This variant is much shorter, but unfortunately takes too long due to exponential branching:
```
f=lambda n,k=1:sorted([k][n:]or(k>4==k%6)*f(n-1,k/3)+f(n-1,k*2))
```
[Answer]
# CJam, ~~29~~ 26 bytes
```
Xari{{2*_Cmd8=*2*)}%1-}*$p
```
*Credit goes to @isaacg for his idea to remove 1's after each iteration, which saved me two bytes directly and another one indirectly.*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Xari%7B%7B2*_Cmd8%3D*2*)%7D%251-%7D*%24p&input=30) (should finish in less than a second).
### How it works
```
Xa       e# Push A := [1].
ri{      e# Read an integer from STDIN and do the following that many times:
  {      e# For each N in A:
    2*   e#     Push I := (N * 2) twice.
    _Cmd e#     Push (I / 12) and (I % 12).
     8=  e#     Push K := (I % 12 == 8).
         e#     (K == 1) if and only if the division ((N - 1) / 3) is exact and
         e#     yields an odd integer. In this case we can compute the quotient 
         e#     as (I / 12) * 2 + 1.
    *2*) e#     Push J := (I / 12) * K * 2 + 1.
         e#     This yields ((N - 1) / 3) when appropriate and 1 otherwise.
  }%     e# Replace N with I and J.
  1-     e# Remove all 1's from A.
         e# This serves three purposes:
         e# 1. Ones have been added as dummy values for inappropriate quotients.
         e# 2. Not allowing 1's in A avoids integers that have already stopped
         e#    from beginning a new cycle. Since looping around has been prevented,
         e#    A now contains all integers of a fixed stopping time.
         e# 3. If A does not contain duplicates, since the maps N -> I and N -> J
         e#      are inyective (exluding image 1) and yield integers of different
         e#      parities, the updated A won't contain duplicates either.
}*       e#
$p       e# print(sort(C))
```
[Answer]
# CJam, 35 bytes
```
1]ri{_"(Z/Y*"3/m*:s:~\L+:L-_&0-}*$p
```
Explanation coming soon. This is a much faster version than the "pretty straight forward" approach (see it in edit history).
[Try it online here](http://cjam.aditsu.net/#code=1%5Dri%7B_%22(Z%2FY*%223%2Fm*%3As%3A~%5CL%2B%3AL-_%260-%7D*%24p&input=25) for `N = 30` which runs in seconds on the online version and instantly in the [Java Compiler](http://sourceforge.net/p/cjam/wiki/)
[Answer]
# Java 8, 123
```
x->java.util.stream.LongStream.range(1,(1<<x)+1).filter(i->{int n=0;for(;i>1;n++)i=i%2<1?i/2:3*i+1;return n==x;}).toArray()
```
When `x` is 30, the program takes 15 minutes and 29 seconds.
## Expanded
```
class Collatz {
    static IntFunction<long[]> f =
            x -> java.util.stream.LongStream.range(1, (1 << x) + 1).filter(i -> {
                int n = 0;
                for (; i > 1; n++)
                    i = i % 2 < 1 ? i / 2 : 3 * i + 1;
                return n == x;
            }).toArray();
    public static void main(String[] args) {
        System.out.println(Arrays.toString(f.apply(15)));
    }
}
```
[Answer]
# Python 2, 118 bytes
Well, I figured that I wouldn't reach the best Python score after seeing @Sp3000's solution. But it looked like a fun little problem, so I wanted to try an independent solution anyway:
```
s={1}
for k in range(input()):
 p,s=s,set()
 for t in p:s.add(2*t);t>4and(t-1)%6==3and s.add((t-1)/3)
print sorted(s)
```
Same thing before stripping whitespace:
```
s={1}
for k in range(input()):
    p,s=s,set()
    for t in p:
        s.add(2 * t)
        t > 4 and (t - 1) % 6 == 3 and s.add((t - 1) / 3)
print sorted(s)
```
This is a very direct implementation of a breadth first search. In each step, we have the set with stopping time `k`, and derive the set with stopping time `k + 1` by adding the possible predecessors of each value `t` in the set from step `k`:
* `2 * t` is always a possible predecessor.
* If `t` can be written as `3 * u + 1`, where `u` is an odd number that is not `1`, then `u` is a predecessor as well.
Takes about 0.02 seconds to run for `N = 30` on my MacBook Pro.
[Answer]
# PHP 5.4+, 178 bytes
The function
```
function c($s,$v=1,$p=[],&$r=[]){$p[]=$v;if(!$s--){return$r[$v][]=$p;}c($s,$v*2,$p,$r);is_int($b=($v-1)/3)&!in_array($b,$p)&$b%2?c($s,$b,$p,$r):0;ksort($r);return array_keys($r);}
```
Test & Output
```
echo "0 - ".implode(',',c(0)).PHP_EOL;
// 0 - 1
echo "1 - ".implode(',',c(1)).PHP_EOL;
// 1 - 2
echo "5 - ".implode(',',c(5)).PHP_EOL;
// 5 - 5,32
echo "9 - ".implode(',',c(9)).PHP_EOL;
// 9 - 12,13,80,84,85,512
echo "15 - ".implode(',',c(15)).PHP_EOL;
// 15 - 22,23,136,138,140,141,150,151,768,832,848,852,853,904,906,908,909,5120,5376,5440,5456,5460,5461,32768
```
S(30) runs in **0.24 seconds\***, returns 732 elements. A couple are 
```
86,87,89,520,522,524,525,528, [ ... ] ,178956928,178956960,178956968,178956970,1073741824
```
\*To save on bytes, I had to add `ksort` and `array_keys` at every step. The only other choice I had was to make a small wrapper function that calls `c()` and then calls `array_keys` and `ksort` on the result once. But due to the time still being decently snappy, I decided to take the performance hit for low byte count. Without the proper sorting & processing, the time is **0.07 seconds** on average for S(30).
If anyone has any clever ways of getting the proper processing only once without too many additional bytes, please let me know! (I store my numbers as array keys, hence the use of `array_keys` and `ksort`)
[Answer]
# C Language
```
#include <stdio.h>
#include <limits.h>    
const int s = 30;
bool f(long i)
{
    int r = 0;
    for(;;)
        if (i < 0 || r > s) return false;
        else if (i == 1) break;
        else{r ++;i = i % 2 ? 3*i + 1 : i/2;}
    return (r==s);
}
void main(){
    for(long i = 1; i < LONG_MAX; i++) if (f(i)) printf("%ld ", i);
}
```
]