The Collatz conjecture is a very well-known conjecture. Take a positive integer; if it's even, divide by 2, else, multiply by 3 and add 1. Repeat until you reach 1
or something else happens. The conjecture is that this process always reaches 1
.
You can also reverse the process. Start at 1
, multiply by 2, and to branch to multiply by 3 and add 1
numbers, when you reach an even number that is 1 (mod 3)
, subtract 1 and divide by 3.
A Collatz path combines the two, trying to get from one number to another with those four operations.
For example, to get to 20
from 1
:
1 *2
2 *2
4 *2
8 *2
16 *2
5 (-1)/3
10 *2
20 *2
You can also get to 3
from 10
by subtracting 1 and dividing by 3.
With these tools, you can traverse a Collatz path from one number to another. For example, the path from 20
to 3
is (divide by 2), (subtract 1, divide by 3).
In short, the available operations are:
n * 2 always
n // 2 if n % 2 == 0
n * 3 + 1 if n % 2 == 1
(n-1) // 3 if n % 6 == 4
Note: not all Collatz paths are short. a(7,3)
could run
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 2, 4, 8, 16, 5, 10, 3
but a shorter path is
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 3
The Challenge
Find the length of the shortest Collatz path between any two positive integers, p
and q
.
- Input is any two positive integers less than
2^20
to avoid integer overflow. The input method is left to the discretion of the golfer. The integers may be the same, in which case, the length of the Collatz path is0
. - Output should be one integer, denoting the length of the shortest Collatz path between
p
andq
.
Test Cases
a(2,1)
1
a(4,1)
1 # 4 -> 1
a(3,1)
6 # 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 1
a(11,12)
11 # 11 -> 34 -> 17 -> 52 -> 26 -> 13
# -> 40 -> 20 -> 10 -> 3 -> 6 -> 12
a(15,9)
20 # 46 -> 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 13
# -> 26 -> 52 -> 17 -> 34 -> 11 -> 22 -> 7 -> 14 -> 28 -> 9
Many thanks to orlp for their help in clarifying this challenge.
As always, if the problem is unclear, please let me know. Good luck and good golfing!