|
| 1 | +/* |
| 2 | +FOREWORD: |
| 3 | +I took help from the internet in designing the recursive method `continuedFraction`. I hope that's ok. |
| 4 | +From this post in particular: https://stackoverflow.com/questions/48094595/convert-fraction-to-continued-fraction. |
| 5 | +That said, I am proud to say that I came up with the idea of continued fraction on my own. |
| 6 | +*/ |
| 7 | + |
| 8 | +// Link to Submission: https://codeforces.com/contest/343/submission/355493183 |
| 9 | + |
| 10 | +/* |
| 11 | +PROBLEM STATEMENT: |
| 12 | +You have unlimited unit resistors. You are given the Req. |
| 13 | +Find the minimum number of unit resistors you need to build a circuit using series and parallel configuration to achieve the Req. |
| 14 | +*/ |
| 15 | + |
| 16 | +/* |
| 17 | +EXPLANATION: |
| 18 | +A fraction can either be proper or improper. |
| 19 | +For improper fractions we can convert it to mixed form i.e for a > b, we can write |
| 20 | + a / b = k + (r / b), where r is a % b and k is floor(a / b). |
| 21 | + r / b is a proper fraction so the next steps are same for both. |
| 22 | +Proper fractions mean the resistors are arranged in parallel. |
| 23 | +The simplest proper fraction to work with is of the type 1 / b, which means b resistors arranged in parallel. |
| 24 | +The first step of the converting a proper fraction to it's continued fraction form is to convert it into an improper fraction. |
| 25 | +So a / b becomes 1 / (b / a). Now we conver b / a to it's mixed form. We keep doing this until we get r / b, where r = 1. |
| 26 | +We keep tracking k, because that gives us number of resistors arranged in series the final b, gives the last few resistors |
| 27 | + that are arranged in parallel. |
| 28 | +*/ |
| 29 | + |
| 30 | + |
| 31 | +import java.util.*; |
| 32 | + |
| 33 | +public class Solution2 { |
| 34 | + static long res = 0; |
| 35 | + static void continuedFraction(long a, long b) { |
| 36 | + if (b == 0) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + long k = a / b; |
| 41 | + long r = a % b; |
| 42 | + |
| 43 | + res += k; |
| 44 | + |
| 45 | + if (r != 0) { |
| 46 | + continuedFraction(b, r); |
| 47 | + } |
| 48 | + } |
| 49 | + public static void main(String[] args) { |
| 50 | + Scanner sc = new Scanner (System.in); |
| 51 | + long a = sc.nextLong(); |
| 52 | + long b = sc.nextLong(); |
| 53 | + |
| 54 | + continuedFraction(a, b); |
| 55 | + |
| 56 | + System.out.println(res); |
| 57 | + sc.close(); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// Time Complexity: O(log(min(a, b))) |
| 62 | +// Space Complexity: O(1) <- Not Sure |
| 63 | + |
0 commit comments