21
1
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.
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.
This is code-golf: shortest program in bytes wins. Good luck!
What of cycles? I did not see a mention of cycle avoidance. Because for S=5, there are 3 values [4, 5, 32] because you can go "1 - 2 - 4 - 1 - 2- 4" – JPMC – 10 years ago
1@JPMC Cycle avoidance is implied by the definition of stopping time. The stopping time of 4 is 2, not 5, because 2 is "the number of times you have to pass it through the Collatz function before it reaches 1." – DLosc – 10 years ago
Ah, forgive me. I was thinking that a number could have multiple stopping times, since multiple paths can lead to it. But that was with respect to building up from 1, not working from N. Sorry about that. – JPMC – 10 years ago
I have a solution that can do S=27 in about 2 minutes on my machine, but runs out of memory on S>=28. Is it valid? – isaacg – 10 years ago
@isaacg Based on what I told FryAmTheEggman earlier, if you can't find some computer that it runs on, I'm going to say no. But if you want to post it and see if someone else has enough memory to test S=30, you could do that. What language is it in? – DLosc – 10 years ago
1@DLosc Pyth, of course. – isaacg – 10 years ago
1
Related, but not golfed: http://math.stackexchange.com/q/470782/20792 and http://math.stackexchange.com/q/1243841/20792
– Pureferret – 10 years ago