(Solved, coded, and written by Sean Rae)
The general gist of this problem is that they present a sequence of numbers that are fractions between 0 and 1. The sequence as it was given is as follows:
1/2
1/3
2/3
1/4
2/4
3/4
1/5
2/5
3/5
4/5 (note that the original erroneously had 4/6 here)
1/6
2/6
3/6
4/6
The input would be two integers that represent positions in the sequence. For instance, if they gave "13" and "7" as inputs, we would have to translate that to "3/6" and "1/5". Once we translate these positions to fractions, we add them together and simplify the result. The final output will be the position in the list of the resulting fraction.
| Input: 2 13 |
Output: 15 |
| Input: 4 3 |
Output: 66 |
First of all, thanks to Dr. Goolsby of the math department for helping me solve this. The code is in black text and the comments are in bright blue.
#include <iostream.h> |
The returnFraction()
subroutine is the part of the code that generates the desired number
sequence. It uses what I call "bins" as a way of
collecting like terms. I chose to have a change in denominator (e.g.
going from thirds to fourths) signal a change in bins. |
// take a position and find its fraction |
I know, I know. This is just a
hack. A better solution would be to logically step through returnFraction(),
line by line, and rewrite it backwards, instead of just repeatedly calling
it. Oh well, it still works. |
// take a fraction and find its location |
| This was based very heavily upon a pseudocode version found in Discrete Mathematics by Richard Johnsonbaugh, on page 155. The basis of the algorithm is mostly self-explanatory, as it is usually covered in introductory programming classes. |
// euclid's greatest common denominator algorithm |
This is just the rest of the code,
mostly the input/output rather than the majority of the effort. Note
that I made use of preprocessor directives (the #define
stuff) to make it easy to change from descriptive output to the output
that the ACM competition required. |
void main() |