给定n> 3,找到n边凸多边形中的对角线数。
根据Wikipedia的说法,在几何学中,对角线是连接多边形或多面体的两个顶点的线段,而这些顶点不在同一条边上。非正式地,任何倾斜线都称为对角线。
例子 :
Input : 5
Output : 5
说明:五个可能的对角线是:AC,AD,BD,BE,CE
解决方案 :
由于对于n边的凸多边形,我们可以从每个顶点绘制n-3个对角线,从而留下两个相邻的顶点及其本身。对于n个顶点,按照这种方式,将有n *(n-3)个对角线,但随后我们将对每个对角线进行两次计算,因此对角线总数变为n *(n-3)/ 2
这是上述公式的代码。
C++
#include
using namespace std;
// C++ function to find number of diagonals
// in n sided convex polygon
int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
int main()
{
int n = 5;
cout << n << " sided convex polygon have ";
cout << numberOfDiagonals(n) << " diagonals";
return 0;
}
Java
// Java function to find number of diagonals
// in n sided convex polygon
public class Diagonals {
static int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
public static void main(String[] args)
{
int n = 5;
System.out.print(n + " sided convex polygon have ");
System.out.println(numberOfDiagonals(n) + " diagonals");
}
}
// This code is contributed by Saket Kumar
Python3
# Python3 program to find number of diagonals
# in n sided convex polygon
def numberOfDiagonals(n):
return n * (n - 3) / 2
# driver code to test above function
def main():
n = 5
print(n , " sided convex polygon have ")
print(numberOfDiagonals(n) , " diagonals")
if __name__ == '__main__':
main()
#this code contributed by 29AjayKumar
C#
// C# function to find number of diagonals
// in n sided convex polygon
using System;
class GFG {
static int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
public static void Main()
{
int n = 5;
Console.Write(n + " sided convex polygon have ");
Console.WriteLine(numberOfDiagonals(n) +
" diagonals");
}
}
// This code is contributed by Sam007
PHP
Javascript
输出 :
5 sided convex polygon have 5 diagonals