Skip to content

Commit 7b58918

Browse files
authored
Merge pull request #317 from verifiedHuman18/day3-q002
Added solution for Day3/q002
2 parents 9e993da + 9f97a69 commit 7b58918

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

842 Bytes
Binary file not shown.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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 convert b / a to it's mixed form ki + (ri / ai). We keep doing this until we get r / ai, where r = 1.
26+
We keep tracking ki, because that gives us number of resistors arranged in series the final ai, 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

Comments
 (0)