Maximum points of intersection n lines
Last Updated :
03 Oct, 2022
You are given n straight lines. You have to find a maximum number of points of intersection with these n lines.
Examples:
Input : n = 4
Output : 6
Input : n = 2
Output :1
Approach :
As we have n number of line, and we have to find the maximum point of intersection using this n line. So this can be done using the combination. This problem can be thought of as a number of ways to select any two lines among n line. As every line intersects with others that are selected.
So, the total number of points = nC2
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long int
ll countMaxIntersect(ll n)
{
return (n) * (n - 1) / 2;
}
int main()
{
ll n = 8;
cout << countMaxIntersect(n) << endl;
return 0;
}
|
Java
public class GFG {
static long countMaxIntersect( long n)
{
return (n) * (n - 1 ) / 2 ;
}
public static void main(String args[])
{
long n = 8 ;
System.out.println(countMaxIntersect(n));
}
}
|
Python3
def countMaxIntersect(n):
return int (n * (n - 1 ) / 2 )
if __name__ = = '__main__' :
n = 8
print (countMaxIntersect(n))
|
C#
using System;
class GFG
{
public static long countMaxIntersect( long n)
{
return (n) * (n - 1) / 2;
}
public static void Main()
{
long n = 8;
Console.WriteLine(countMaxIntersect(n));
}
}
|
PHP
<?PHP
function countMaxIntersect( $n )
{
return ( $n ) * ( $n - 1) / 2;
}
$n = 8;
echo countMaxIntersect( $n ) . "\n" ;
?>
|
Javascript
<script>
function countMaxIntersect(n)
{
return (n) * (n - 1) / 2;
}
var n = 8;
document.write( countMaxIntersect(n) );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...