Egyptian Fractions
Time limit1sMemory limit128 MB
Apply the greedy Egyptian fraction algorithm to M/N, capping each remainder's denominator below 1,000,000, and print the unit fraction denominators.
- Level
Medium5 of 10
- Topics
- Greedy, Number theory, Math, Simulation
- Solved
- No attempts yet
Problem
The ancient Egyptians used a distinctive way to write fractions. They created a hieroglyph for each unit fraction (a fraction whose numerator is ) and represented other fractions by adding unit fractions together. Because this system could not directly express a fraction with a numerator greater than , every fraction was written as a sum of unit fractions.
For example, can be written as
A fraction may have several such representations. For instance, can also be written as
Given a fraction , we want to express it as a sum of unit fractions using the greedy method. The greedy method repeatedly subtracts the largest unit fraction that can be taken from the current remainder, until the remainder becomes . For example, applying the greedy method to gives
To keep the denominators from growing too large, we add the following restriction. After subtracting a unit fraction, the denominator of the remaining fraction (in lowest terms) must always be less than . If subtracting the largest possible unit fraction would leave a remainder whose denominator is or more, that unit fraction may not be used. In that case we try the next unit fractions in turn ( instead of , increasing the denominator by each time) and use the largest one for which the remaining denominator drops below .
For example, starting from , the first two unit fractions are and , leaving . The largest unit fraction that could be subtracted next is , but
leaves a denominator greater than . So cannot be used, and subtracting the next unit fraction gives
which satisfies the restriction. The final answer is therefore
Every fraction can also be written as a sum of unit fractions that all share the same denominator; for example, equals added times. Hence there is no fraction that cannot be represented by this method.
Input
The input consists of several test cases. Each test case is a single line containing two integers and separated by a space, denoting the fraction . It is guaranteed that and that . The last line contains 0 0, which is not processed.
Output
For each test case, output on one line the denominators of the unit fractions produced by the greedy method described above, separated by spaces, so that
holds. Print them in the order .