Given that person A takes a days to do a certain piece of work while person B takes b days to do the same work. If A and B started the work together and n days before the completion of work, A leaves the work. Find the total number of days taken to complete work.
Examples:Â
Input: a = 10, b = 20, n = 5Â
Output: 10Input: a = 5, b = 15, n = 3Â
Output: 6Â Â
Approach: Let D be the total number of days to complete the work. A and B work together for D – n days. So, Â
(D – n) * (1/a + 1/b) + (n) * (1/b) = 1Â
D * (1/a + 1/b) – (n/a) – (n/b) + (n/b) = 1Â
D * (1/a + 1/b) = (n + a) / aÂ
D = b * (n + a) / (a + b)Â
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; Â
// Function to return the // number of days required int numberOfDays( int a, int b, int n) { Â Â Â Â int Days = b * (n + a) / (a + b); Â
    return Days; } Â
// Driver code int main() { Â Â Â Â int a = 10, b = 20, n = 5; Â
    cout << numberOfDays(a, b, n); Â
    return 0; } |
Java
// Java implementation of the approach import java.io.*; Â
class GFG { Â Â Â Â Â // Function to return the // number of days required static int numberOfDays( int a, int b, int n) { Â Â Â Â int Days = b * (n + a) / (a + b); Â
    return Days; } Â
// Driver code public static void main (String[] args) { Â
    int a = 10 , b = 20 , n = 5 ;     System.out.println (numberOfDays(a, b, n)); Â
} } Â
// This code is contributed by jit_t |
Python3
# Python3 implementation of the approach   # Function to return the # number of days required def numberOfDays(a, b, n): Â
    Days = b * (n + a) / / (a + b)       return Days Â
# Driver code if __name__ = = "__main__" : Â
    a = 10     b = 20     n = 5       print (numberOfDays(a, b, n)) Â
# This code is contributed by rrrtnx |
C#
// C# implementation of the approach using System; Â
class GFG {          // Function to return the     // number of days required     static int numberOfDays( int a, int b, int n)     {         int Days = b * (n + a) / (a + b);              return Days;     }          // Driver code     public static void Main ()     {              int a = 10, b = 20, n = 5;         Console.WriteLine(numberOfDays(a, b, n));          } } Â
// This code is contributed by AnkitRai01 |
Javascript
<script> // javascript implementation of the approach Â
    // Function to return the     // number of days required     function numberOfDays(a , b , n)     {         var Days = b * (n + a) / (a + b);         return Days;     } Â
    // Driver code     var a = 10, b = 20, n = 5;     document.write(numberOfDays(a, b, n)); Â
// This code is contributed by Rajput-Ji </script> |
10
Â
Time Complexity: O(1), since there is only basic arithmetic operation.
Auxiliary Space: O(1), since no extra space has been taken.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!