A maintenance shaft in an old factory holds a row of gears, each stamped with a tooth count. Whenever two gears with different tooth counts sit right next to each other on the shaft, the mesh grinds and slips, so the crew always slides in a small synchronizer gear between them. A synchronizer's own tooth count is fixed by the two gears it sits between: it always equals their greatest common divisor. The crew installs exactly one synchronizer after every gear except the last one, so the shaft ends up longer than it started. Given the tooth counts of the original gears in shaft order, report the tooth counts of the entire shaft — originals and synchronizers together — in the final mounting order.
Line 1: a single integer n, the number of original gears.
Line 2: n space-separated integers, the tooth counts of the original gears in shaft order.
Print one line containing the tooth counts of the full shaft after every synchronizer gear has been installed, space-separated, in shaft order. The full shaft has 2n - 1 gears in total (just the one original gear if n = 1).
Example 1
Input
4 18 6 10 3
Expected
18 6 6 2 10 1 3
Explanation
The shaft has 4 gears: 18, 6, 10, 3. Between 18 and 6 the synchronizer is gcd(18,6)=6; between 6 and 10 it's gcd(6,10)=2; between 10 and 3 it's gcd(10,3)=1. Reading the whole shaft in order gives 18 6 6 2 10 1 3.
Example 2
Input
1 7
Expected
7
Explanation
With only one gear on the shaft there is no adjacent pair, so no synchronizer is installed and the shaft is unchanged: just 7.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →