|
| 1 | +Question of the day: https://codefights.com/challenge/hT9JyzWh77Y6NR2Qd |
| 2 | + |
| 3 | +Stephan is a little boy who loves math. It came as a revelation to him that |
| 4 | +one can define the greatest common divisor for rational numbers, not just |
| 5 | +for integers. He's decided to dig into the subject and analyze the properties |
| 6 | +of this new-to-him GCD. |
| 7 | + |
| 8 | +Stephan needs lots of GCDs to gather all possible information about them. But |
| 9 | +Stephan is still a little boy and he can't calculate the GCD of two numbers as |
| 10 | +quickly as he'd like. So he asks for your help: Given float numbers x and y, |
| 11 | +calculate their greatest common divisor. |
| 12 | + |
| 13 | +It is guaranteed that both x and y will have at most 5 digits after the decimal |
| 14 | +point. |
| 15 | + |
| 16 | +Example: |
| 17 | + |
| 18 | +For `x = 2.4` and `y = 4.8`, the output should be |
| 19 | +`helpingStephan(x, y) = 2.4`. |
| 20 | + |
| 21 | +## Ideas |
| 22 | + |
| 23 | +How do I even find GCD without decimals? uhhhhh.... |
| 24 | + |
| 25 | +Prime factorization? That seems complicated but doable for small numbers. |
| 26 | +I can get the prime factorization of each number by repeatedly dividing |
| 27 | +primes in increasing magnitude up to the value of the number, and keeping |
| 28 | +the number of times each prime divides into the number in a hash. Then get |
| 29 | +the primes that each number has in common and get the `min` between them. |
| 30 | + |
| 31 | +Let me just google this.. |
| 32 | + |
| 33 | +Aha! [Euclid's Algorithm](https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm) |
| 34 | +I totally learned this in Algorithms class in college but forgot it existed. |
| 35 | + |
| 36 | +Not sure what the runtime is for this algorithm, but this stack overflow post |
| 37 | +kinda explains it: http://stackoverflow.com/questions/3980416/time-complexity-of-euclids-algorithm |
| 38 | + |
| 39 | +So I could just change the floats that I'm given into ints by multiplying by |
| 40 | +a factor of 10, apply Euclid's Algorithm in `O(n)` runtime where `n` is |
| 41 | +proportional to the value of the input numbers, and then divide by the earlier |
| 42 | +factor of 10 I used to multiply. |
| 43 | + |
| 44 | +## Code |
| 45 | + |
| 46 | +[Python](helpingStephan.py) |
| 47 | + |
| 48 | +## Follow up |
| 49 | + |
| 50 | +Floats.. https://docs.python.org/2/tutorial/floatingpoint.html#tut-fp-issues |
0 commit comments