假设人A花了几天的时间做某件工作,而人B花了b天的时间做同样的工作。如果A和B一起开始工作,并且在工作完成前n天,则A离开工作。查找完成工作所需的总天数。
例子:
Input: a = 10, b = 20, n = 5
Output: 10
Input: a = 5, b = 15, n = 3
Output: 6
方法:设D为完成工作的总天数。 A和B一起工作了D – n天。所以,
(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)
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
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
输出:
10
时间复杂度: O(1)
辅助空间: O(1)