11
What you need to do is create a function/program that takes a decimal as input, and outputs the result of repeatedly taking the reciprocal of the fractional part of the number, until the number becomes an integer.
More specifically, the process is as follows:
Let x be the input
If x is an integer, output it.
Otherwise: \$x \leftarrow \frac{1}{\mathrm{frac}(x)}\$. Go back to 2.
\$\mathrm{frac}(x)\$ is the fractional component of \$x\$, and equals \$x - \left\lfloor x \right\rfloor\$. \$\left\lfloor x \right\rfloor\$ is the floor of x, which is the greatest integer less than \$x\$.
Test cases:
0 = 0
0.1 = 1/10 -> 10
0.2 = 1/5 -> 5
0.3 = 3/10 -> 10/3 -> 1/3 -> 3
0.4 = 2/5 -> 5/2 -> 1/2 -> 2
0.5 = 1/2 -> 2
0.6 = 3/5 -> 5/3 -> 2/3 -> 3/2 -> 1/2 -> 2
0.7 = 7/10 -> 10/7 -> 3/7 -> 7/3 -> 1/3 -> 3
0.8 = 4/5 -> 5/4 -> 1/4 -> 4
0.9 = 9/10 -> 10/9 -> 1/9 -> 9
1 = 1
3.14 = 157/50 -> 7/50 -> 50/7 -> 1/7 -> 7
6.28 = 157/25 -> 7/25 -> 25/7 -> 4/7 -> 7/4 -> 3/4 -> 4/3 -> 1/3 -> 3
Summary for 0 to 1 at increments of 0.1: 0, 10, 5, 3, 2, 2, 2, 3, 4, 9, 1
This is code-golf, so fewest bytes wins.
Clarifications:
- "Bonus points" for no round-off error
- Should work for any non-negative rational number (ignoring round-off error)
- You can, but don't have to output the steps taken
- You can take input as a decimal, fraction, or pair of numbers, which can be in a string.
Sorry for all the issues, this is my first question on this website.
The fact that this terminates is closely related to the possibility of expressing a decimal in continued fraction. – Leaky Nun – 2017-07-02T14:45:06.623
4Are we expected to output floats? They cause some precision issue. – Leaky Nun – 2017-07-02T14:45:31.390
7Could you detail the process a little bit more? I'm unsure as to what "reciprocal of the fractional part of the number" entails, and the test cases don't help much either – Post Rock Garf Hunter – 2017-07-02T14:51:06.900
4Can we take two integers as input to represent a rational number? – Leaky Nun – 2017-07-02T14:58:58.247
I thought you need to output the numbers in the process as well. – Leaky Nun – 2017-07-02T14:59:19.550
Optionally. You can, but don't have to. – Solomon Ucko – 2017-07-02T15:18:07.670
1This is equal to the final element of the simple continued fraction of the input. – isaacg – 2017-07-02T16:08:37.477
Are the test cases the only input we need to be able to handle? – Shaggy – 2017-07-02T19:31:59.607
@Shaggy No.These are just examples. If you encounter round-off error, you can post the version with round-off error and the fixed version together. – Solomon Ucko – 2017-07-02T22:59:22.923
Please add more test cases, so, for numbers with more than one decimal place and numbers greater than 1. – Shaggy – 2017-07-03T08:19:24.017