给定一个正方形,正方形的每一边都有N个点,并且这些点都不与正方形的角重合。任务是计算使用这4 * N个点(正方形每边的 N 个点)作为三角形的顶点可以形成的三角形总数。
例子:
Input: N = 1
Output: 4
There is one point on each side. So we can make three rectangles by leaving one point and picking other three points out of the four.
Input: N = 2
Output: 56
方法:在4*N个点中选择3个点的方法数为(4*N) C 3 。然而,它们中的一些不形成三角形。当所有三个选定的点都在正方形的同一侧时,就会发生这种情况。这些三元组的数量对于每一边是N C 3 ,即总共4 * N C 3 。因此,所需的三角形数将为( (4 * N) C 3 ) – (4 * N C 3 ) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count
// of possible triangles
int noOfTriangles(int n)
{
int y = 4 * n;
return ((y * (y - 2) * (y - 1))
- (4 * n * (n - 2) * (n - 1)))
/ 6;
}
// Driver code
int main()
{
int n = 1;
cout << noOfTriangles(n);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to return the count
// of possible triangles
static int noOfTriangles(int n)
{
int y = 4 * n;
return ((y * (y - 2) * (y - 1)) -
(4 * n * (n - 2) * (n - 1))) / 6;
}
// Driver code
public static void main (String[] args)
{
int n = 1;
System.out.println(noOfTriangles(n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to return the count
# of possible triangles
def noOfTriangles(n):
y = 4 * n
return ((y * (y - 2) * (y - 1)) -
(4 * n * (n - 2) * (n - 1)))// 6
# Driver code
n = 1
print(noOfTriangles(n))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to return the count
// of possible triangles
static int noOfTriangles(int n)
{
int y = 4 * n;
return ((y * (y - 2) * (y - 1)) -
(4 * n * (n - 2) * (n - 1))) / 6;
}
// Driver code
public static void Main (String[] args)
{
int n = 1;
Console.WriteLine(noOfTriangles(n));
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
4
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。