Write a program to determine the distance(D) between two points traveled by a boat, given the speed of boat in still water(B), the speed of the stream(S), the time taken to row a place and come back i.e T.
Examples:
Input : B = 5, S = 1, T = 1
Output : D = 2.4
Input : B = 5, S = 2, T = 1
Output : D = 2.1
Formula for distance is D = T*(B^2 – S^2)/ (2*B)
How does this formula work?
Time taken when person goes upstream,
t1 = D/(B-S)
Time taken when person goes downstream,
t2 = D/(B+S)
We are given t1 + t2 = T
So, D/(B-S) + D/(B+S) = T
D = T*(B^2 - S^2)/ (2*B)
C++
#include <iostream>
using namespace std;
float distance(float T, float B, float S)
{
return (T * (((B * B) - (S * S)) / (2 * B)));
}
int main()
{
float T = 1;
float B = 5;
float S = 1;
cout << "The distance between two points via boat = "
<< distance(T, B, S) << " km";
return 0;
}
|
Java
import java.io.*;
class GFG {
static float distance(float T, float B, float S)
{
return (T * (((B * B) - (S * S)) / (2 * B)));
}
public static void main (String[] args)
{
float T = 1;
float B = 5;
float S = 1;
System.out.println("The distance between two points via boat = "
+ distance(T, B, S) + " km");
}
}
|
Python3
def distance( T, B, S):
return (T * (((B * B) - (S * S)) / (2 * B)))
if __name__ == "__main__":
T = 1
B = 5
S = 1
print("The distance between two "+
"points via boat =",
distance(T, B, S), "km")
|
C#
using System;
class GFG {
static float distance(float T, float B, float S)
{
return (T * (((B * B) - (S * S)) / (2 * B)));
}
public static void Main()
{
float T = 1;
float B = 5;
float S = 1;
Console.WriteLine("The distance between two points via boat = " +
distance(T, B, S) + " km");
}
}
|
Javascript
<script>
function distance(T,B,S)
{
return (T * (((B * B) - (S * S)) / (2 * B)));
}
var T = 1;
var B = 5;
var S = 1;
document.write("The distance between " +
"two points via boat = " +
distance(T, B, S) + " km ");
</script>
|
Output:
The distance between two points via boat = 2.4 km
Time Complexity: O(1)
Auxiliary Space: O(1)