The easiest way I can think of is to start a nested loop over p and q , and then sort the result. In Python:
N=100 products_of_powers_of_2and3 = [] power_of_2 = 1 while power_of_2 < N: product_of_powers_of_2and3 = power_of_2 while product_of_powers_of_2and3 < N: products_of_powers_of_2and3.append(product_of_powers_of_2and3) product_of_powers_of_2and3 *= 3 power_of_2 *= 2 products_of_powers_of_2and3.sort() print products_of_powers_of_2and3
result
[1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 27, 32, 36, 48, 54, 64, 72, 81, 96]
(before sorting products_of_powers_of_2and3 there is
[1, 3, 9, 27, 81, 2, 6, 18, 54, 4, 12, 36, 8, 24, 72, 16, 48, 32, 96, 64]
)
Given that the size of products_of_powers_of_2and3 is of the order of log 2 N * log 3 N, the list does not grow very quickly and its sorting is not performed seem particularly inefficient. For instance. even with N = 1 million, the list is very short, 142 items, so you do not need to worry.