37
3
Introduction
In this challenge, we will be dealing with a certain ordering of the positive integers. The ordering goes like this:
3, 5, 7, 9, 11, ...
2*3, 2*5, 2*7, 2*9, 2*11, ...
4*3, 4*5, 4*7, 4*9, 4*11, ...
8*3, 8*5, 8*7, 8*9, 8*11, ...
16*3, 16*5, 16*7, 16*9, 16*11, ...
...
... 64, 32, 16, 8, 4, 2, 1
We first list all odd integers greater than 1 in ascending order. Then we list two times odd integers greater than 1, then 4 times, then 8 times, and so on: for all k, we list 2k times the odd integers greater than 1 in ascending order. Finally, we list the powers of two in descending order, ending at 1. Every positive integer occurs in this "list" exactly once.
More explicitly, consider two distinct positive integers A = n·2p and B = m·2q, where n, m ≥ 1 are odd, and p, q ≥ 0. Then A comes before B in the ordering, if one of the following conditions holds:
- n > 1, m > 1 and p < q
- 1 < n < m and p = q
- n > m = 1
- n = m = 1 and p > q
This ordering appears in the surprising mathematical result known as Sharkovskii's theorem, which concerns the periodic points of dynamical systems. I will not go into the details here.
The task
Your task in this challenge is to compute the above ordering. Your inputs are two positive integers A and B, which may be equal. Your output is a truthy value if A comes before B in the ordering, and a falsy value otherwise. If A = B, your output should be truthy. You can take A and B in either order, as long as you're consistent.
You don't have to worry about integer overflow, but your algorithm should theoretically work for arbitrarily large inputs.
Test cases
Truthy instances
3 11
9 6
48 112
49 112
158 158
36 24
14 28
144 32
32 32
32 8
3 1
1 1
Falsy instances
1 2
1 5
11 5
20 25
2 8
256 255
256 257
72 52
2176 1216
2176 2496
Nice. I didn't think about using recursion here. Would
a&1|~b&1&f(a/2,b/2)
work? – Arnauld – 2016-12-20T17:02:20.780@Arnauld I'm not sure, I was worried that it would loop indefinitely. – Neil – 2016-12-20T17:07:06.807
It can't because
b<2
will eventually be true. Now, another problem is that you'll process more iterations than needed and get floating point values. But I can't find any counterexample that would not work as expected. – Arnauld – 2016-12-20T17:24:55.393@Arnauld Ah, right, I wasn't using
b<2
originally, but I guess it will work now. – Neil – 2016-12-20T19:35:24.020@Arnauld Better still, since
f(a/2,b/2)
only returns0
,1
,false
ortrue
, I don't even need the&1
. – Neil – 2016-12-20T21:49:43.117