Skip to content

Commit 7fc2770

Browse files
authored
Merge pull request #291 from dwivediprashant/code/day-3-que-2
Code : solved que-2 of day-3
2 parents 8d5315c + 1cd97af commit 7fc2770

1 file changed

Lines changed: 96 additions & 0 deletions

File tree

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/*
2+
Problem Statement:
3+
Mike has an unlimited number of unit resistors (each with resistance = 1).
4+
5+
Using these resistors, he can create new elements in two ways:
6+
1. Series connection:
7+
- New resistance = current resistance + 1
8+
2. Parallel connection:
9+
- New resistance = current resistance / (current resistance + 1)
10+
11+
Given a target resistance as a reduced fraction a / b,
12+
the task is to find the minimum number of unit resistors
13+
needed to build exactly this resistance.
14+
15+
It is guaranteed that a solution always exists.
16+
17+
---------------------------------------
18+
Observation:
19+
Instead of actually building resistor networks, we can
20+
work directly with the fraction a / b.
21+
22+
At every step:
23+
- If a > b, we reduce a using b.
24+
- If b > a, we reduce b using a.
25+
26+
Each reduction corresponds to adding one unit resistor.
27+
28+
---------------------------------------
29+
Important Insight:
30+
When a > b:
31+
- a can be reduced by subtracting b multiple times at once.
32+
- This is equivalent to using (a / b) resistors.
33+
34+
Similarly, when b > a:
35+
- b can be reduced using a.
36+
- This uses (b / a) resistors.
37+
38+
This process continues until one value becomes zero.
39+
40+
---------------------------------------
41+
Approach:
42+
1. Read integers a and b.
43+
2. Initialize a counter for resistors used.
44+
3. While both a and b are non-zero:
45+
- If a > b:
46+
- Add a / b to the counter.
47+
- Set a = a % b.
48+
- Else:
49+
- Add b / a to the counter.
50+
- Set b = b % a.
51+
4. Output the counter.
52+
53+
---------------------------------------
54+
Time Complexity:
55+
O(log(min(a, b)))
56+
57+
---------------------------------------
58+
Space Complexity:
59+
O(1)
60+
61+
---------------------------------------
62+
Constraints:
63+
1 ≤ a, b ≤ 10^18
64+
---------------------------------------
65+
*/
66+
67+
/*--- submission link
68+
https://codeforces.com/contest/343/submission/355464586
69+
*/
70+
71+
import java.util.*;
72+
73+
public class Solution2 {
74+
public static void main(String[] args) {
75+
76+
Scanner sc = new Scanner(System.in);
77+
78+
long a = sc.nextLong();
79+
long b = sc.nextLong();
80+
81+
long used = 0;
82+
83+
// keep reducing until one value becomes zero
84+
while (a != 0 && b != 0) {
85+
if (a > b) {
86+
used += a / b;
87+
a = a % b;
88+
} else {
89+
used += b / a;
90+
b = b % a;
91+
}
92+
}
93+
94+
System.out.println(used);
95+
}
96+
}

0 commit comments

Comments
 (0)