给定一个数 n,我们需要找到 n 个圆相交的最大次数。
例子:
Input : n = 2
Output : 2
Input : n = 3
Output : 6
描述和推导
正如我们在上图中看到的,对于每对圆,最多可以有两个相交点。因此,如果我们有 n 个圆,那么可以有n C 2对圆,其中每对圆都有两个交点。因此,由此我们可以得出结论,通过查看所有可能的圆对,可以为 n 个圆的最大交点数得出数学公式为2 * n C 2 。
2 * n C 2 = 2 * n * (n – 1)/2 = n * (n-1)
C++
// CPP program to find maximum umber of
// intersections of n circles
#include
using namespace std;
// Returns maximum number of intersections
int intersection(int n)
{
return n * (n - 1);
}
int main()
{
cout << intersection(3) << endl;
return 0;
}
// This code is contributed by
// Manish Kumar Rai.
Java
// Java program to find maximum umber of
// intersections of n circles
import java.io.*;
public class GFG {
// for the calculation of 2*(nC2)
static int intersection(int n)
{
return n * (n - 1);
}
public static void main(String[] args) throws IOException
{
System.out.println(intersection(3));
}
}
// This code is contributed by
// Manish Kumar Rai
Python3
# python program to find maximum umber of
# intersections of n circles
# Returns maximum number of intersections
def intersection(n):
return n * (n - 1);
# Driver code
print(intersection(3))
# This code is contributed by Sam007
C#
// C# program to find maximum umber of
// intersections of n circles
using System;
class GFG {
// for the calculation of 2*(nC2)
static int intersection(int n)
{
return n * (n - 1);
}
// Driver Code
public static void Main()
{
Console.WriteLine(intersection(3));
}
}
// This code is contributed by Sam007
php
Javascript
输出:
6
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。