8

How can I efficiently generate the first N elements of the sequence $3^i 5^j 7^k$, where $i,j,k \in \mathbb{N}$?

I've googled around a bit and found the sequence in OEIS, but I don't really see a simple way of generating it.

Raphael
  • 73,212
  • 30
  • 182
  • 400
Katy Perry
  • 91
  • 1

2 Answers2

15

Here I assume $0\in \mathbb N$. If you disagree start with $105$.

Let $S$ be the sequence of numbers of the form $3^i5^j7^k$. Our task is to generate these numbers in order. Apart from $1$ each number added is of the form $3\cdot x$, $5\cdot y$ or $7\cdot z$ where $x,y,z$ are previous numbers in the sequence. We can generate $S$ by shifting $x,y,z$ along the sequence.

So, first put $1$ into $S$, and set $x,y,z$ equal to $1$.

Now repeat: Take the minimum value $m$ of $3\cdot x$, $5\cdot y$ and $7\cdot z$, and add $m$ to the sequence $S$. The $x,y,z$ for which the minimum was taken are shifted to the next element of $S$. This might be more than one, or even all three.

$\newcommand{\ul}[1]{\underline{#1}}$ $\begin{array}{r|rr|rr|rr} S & x & {}*3 & y & {}*5 & z & {}*7 & \\\hline 1 & 1 & \ul{3} & 1 & 5 & 1 & 7 \\ 3 & 3 & 9 & & \ul{5} & & 7 \\ 5 & & 9 & 3 & 15 & & \ul{7} \\ 7 & & \ul{9} & & 15 & 3 & 21 \\ 9 & 5 & \ul{15} & & \ul{15} & & 21 \\ 15 & 7 & \ul{21} & 5 & 25 & & \ul{21} \\ 21 & 9 & 27 & & \ul{25} & 5 & 35 \\ 25 & & \ul{27} & 7 & 35 & & 35 \\ 27 & 15 & 45 & & \ul{35} & & \ul{35} \\ 35 & & \ul{45} & 9 & \ul{45} & 7 & 49 \\ 45 & 21 & 63 & 15 & 75 & & 49 \end{array}$

Works in linear time, as we need to take the minimum of three numbers in each step.

Hendrik Jan
  • 31,459
  • 1
  • 54
  • 109
5

Consider a weighted, directed graph, with a vertex $v_i$ for $i\in\mathbb{N}$. There is an edge with weight $j-i$ from $v_i$ to $v_j$ if $j\in\{3i,5i,7i\}$.

Now run Dijkstra's shortest path algorithm. It will expand exactly the nodes from your sequence and do so in order. This gives an $n\log n$ algorithm to enumerate the first $n$ elements, since the graph has maximum out-degree $3$.

Tom van der Zanden
  • 13,493
  • 1
  • 39
  • 56