Count of Unique Direct Path Between N Points On a Plane
Last Updated :
11 Oct, 2021
Given N points on a plane, where each point has a direct path connecting it to a different point, the task is to count the total number of unique direct paths between the points.
Note: The value of N will always be greater than 2.
Examples:
Input: N = 4
Output: 6
Explanation: Think of 4 points as a 4 sided polygon. There will 4 direct paths (sides of the polygon) as well as 2 diagonals (diagonals of the polygon). Hence the answer will be 6 direct paths.
Input: N = 3
Output: 3
Explanation: Think of 3 points as a 3 sided polygon. There will 3 direct paths (sides of the polygon) as well as 0 diagonals (diagonals of the polygon). Hence the answer will be 3 direct paths.
Approach: The given problem can be solved using an observation that for any N-sided there are (number of sides + number of diagonals) direct paths. For any N-sided polygon, there are N sides and N*(N – 3)/2 diagonals. Therefore, the total number of direct paths is given by N + (N * (N – 3))/2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countDirectPath( int N)
{
return N + (N * (N - 3)) / 2;
}
int main()
{
int N = 5;
cout << countDirectPath(N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countDirectPath( int N)
{
return N + (N * (N - 3 )) / 2 ;
}
public static void main(String []args)
{
int N = 5 ;
System.out.print(countDirectPath(N));
}
}
|
Python3
def countDirectPath(N):
return N + (N * (N - 3 )) / / 2
if __name__ = = "__main__" :
N = 5
print (countDirectPath(N))
|
C#
using System;
public class GFG
{
static int countDirectPath( int N)
{
return N + (N * (N - 3)) / 2;
}
public static void Main( string []args)
{
int N = 5;
Console.Write(countDirectPath(N));
}
}
|
Javascript
<script>
function countDirectPath(N) {
return N + Math.floor((N * (N - 3)) / 2);
}
let N = 5;
document.write(countDirectPath(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...