📜  如果第二人以给定速度行驶,则第二人超越第一人的小时数

📅  最后修改于: 2021-04-29 18:32:54             🧑  作者: Mango

给定三个整数ABK。最初,第一个人比第二个人领先K kms。在每个小时中,第一个人向前行驶A公里,第二个人向前行驶B公里。任务是打印第二个人越过第一个人的小时数。如果无法这样做,请打印-1

例子:

天真的方法是线性检查每个小时,并在第二个人向前移动第一个人时打印第n个小时。
一种有效的方法是用数学方法解决问题。当第二个人领先于第一个人时,小时数将为K /(B – A)+ 1 。由于您需要覆盖K公里,因此花费的时间为K /(B – A) ,其中B – A是第二个人相对于第一个人的速度。如果A≥B,那么第二个人就不可能越过第一个人。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to return the number of
// hours for the second person to move ahead
int findHours(int a, int b, int k)
{
    if (a >= b)
        return -1;
 
    // Time taken to equalize
    int time = k / (b - a);
 
    // Time taken to move ahead
    time = time + 1;
 
    return time;
}
 
// Driver code
int main()
{
    int a = 4, b = 5, k = 1;
    cout << findHours(a, b, k);
    return 0;
}


Java
// Java implementation of the above approach
import java.io.*;
 
class GFG
{
     
// Function to return the number of
// hours for the second person to move ahead
static int findHours(int a, int b, int k)
{
    if (a >= b)
        return -1;
 
    // Time taken to equalize
    int time = k / (b - a);
 
    // Time taken to move ahead
    time = time + 1;
 
    return time;
}
 
// Driver code
public static void main (String[] args)
{
 
        int a = 4, b = 5, k = 1;
        System.out.println (findHours(a, b, k));
}
}
 
// The code is contributed by ajit..@23


Python3
# Python3 implementation of the above approach
 
# Function to return the number of
# hours for the second person to move ahead
def findHours(a, b, k):
    if (a >= b):
        return -1
 
    # Time taken to equalize
    time = k // (b - a)
 
    # Time taken to move ahead
    time = time + 1
 
    return time
 
 
# Driver code
 
a = 4
b = 5
k = 1
print(findHours(a, b, k))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach
using System;
 
class GFG
{
         
// Function to return the number of
// hours for the second person to move ahead
static int findHours(int a, int b, int k)
{
    if (a >= b)
        return -1;
 
    // Time taken to equalize
    int time = k / (b - a);
 
    // Time taken to move ahead
    time = time + 1;
 
    return time;
}
 
// Driver code
static public void Main ()
{
    int a = 4, b = 5, k = 1;
    Console.Write(findHours(a, b, k));
}
}
 
// The code is contributed by ajit.


Javascript


输出:
2