Consider two people moving in opposite direction with speeds U meters/second and V meters/second respectively. The task is to find how long will take to make the distance between them X meters.
Examples:
Input: U = 3, V = 3, X = 3
Output: 0.5
After 0.5 seconds, policeman A will be at distance 1.5 meters
and policeman B will be at distance 1.5 meters in the opposite direction
The distance between the two policemen is 1.5 + 1.5 = 3
Input: U = 5, V = 2, X = 4
Output: 0.571429
Approach: It can be solved using distance = speed * time. Here, distance would be equal to the given range i.e. distance = X and speed would be the sum of the two speeds because they are moving in the opposite direction i.e. speed = U + V.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double getTime( int u, int v, int x)
{
double speed = u + v;
double time = x / speed;
return time ;
}
int main()
{
double u = 3, v = 3, x = 3;
cout << getTime(u, v, x);
return 0;
}
|
Java
class GFG
{
static double getTime( int u, int v, int x)
{
double speed = u + v;
double time = x / speed;
return time;
}
public static void main(String[] args)
{
int u = 3 , v = 3 , x = 3 ;
System.out.println(getTime(u, v, x));
}
}
|
Python3
def getTime(u, v, x):
speed = u + v
time = x / speed
return time
if __name__ = = "__main__" :
u, v, x = 3 , 3 , 3
print (getTime(u, v, x))
|
C#
using System;
class GFG
{
static double getTime( int u, int v, int x)
{
double speed = u + v;
double time = x / speed;
return time;
}
public static void Main()
{
int u = 3, v = 3, x = 3;
Console.WriteLine(getTime(u, v, x));
}
}
|
PHP
<?php
function getTime( $u , $v , $x )
{
$speed = $u + $v ;
$time = $x / $speed ;
return $time ;
}
$u = 3; $v = 3; $x = 3;
echo getTime( $u , $v , $x );
?>
|
Javascript
<script>
function getTime(u, v, x)
{
let speed = u + v;
let time = x / speed;
return time;
}
let u = 3, v = 3, x = 3;
document.write(getTime(u, v, x));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
22 Jun, 2022
Like Article
Save Article