You are given two hour glasses. They measure M and N minutes respectively. You wish to use these two hour glasses to measure a target period of T minutes. Each hour glass consists of two glass bowls connected by a narrow section (the "narrows") where sand can flow from one bowl into the other. If all of the sand is in the lower bowl and the hour glass is turned upside down ("flipped"), the sand will flow into the other bowl (which is now the lower bowl) in M or N minutes, respectively.
Initially (at time = 0), all of the sand is in the lower bowl in each of the hour glasses, and both hour glasses are flipped. Subsequently, one can flip one or both of the hour glasses according to the following rules.
- When only one of the hour glasses expires at a particular instant, one has four choices of action:
- flip the hour glass that expired;
- flip the hour glass that did not expire;
- flip both hour glasses;
- do not flip either one, just let one hour glass sit idle until the other one expires.
- When both of the hour glasses happen to expire simultaneously, or if one hour glass has been sitting idle and the other one has just expired, one must flip at least one of the hour glasses.
- Any hour glass may be flipped only at an instant when either the same hour glass, or the other one, or both have just expired.
A particular time T can be measured if there is a sequence of hour glass flips such that one (or both) of the hour glasses expires at time T during the sequence. You may assume that flipping an hour glass is instantaneous and does not take any time.