给定n>3,求n边凸多边形中的对角线数。 根据 维基百科 ,在几何学中,对角线是连接多边形或多面体的两个顶点的线段,当这些顶点不在同一条边上时。非正式地说,任何倾斜的线都被称为对角线。
null
例如:
Input : 5 Output : 5
说明:五种可能的对角线是:AC、AD、BD、BE、CE
因为对于n边凸多边形,从每个顶点,我们可以画出n-3条对角线,留下两个相邻的顶点和它本身。按照这种方法,对于n个顶点,将有n*(n-3)条对角线,但是我们将计算每个对角线两次,这样对角线的总数将变成n*(n-3)/2 下面是上述公式的代码。
C++
#include <iostream> 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
<?php // PHP function to find number // of diagonals in n sided // convex polygon function numberOfDiagonals( $n ) { return $n * ( $n - 3) / 2; } // Driver Code $n = 5; echo $n , " sided convex polygon have " ; echo numberOfDiagonals( $n ) , " diagonals" ; // This code is contributed by aj_36 ?> |
Javascript
<script> // Javascript function to find number of // diagonals in n sided convex polygon function numberOfDiagonals(n) { return n * (n - 3) / 2; } // Driver code var n = 5; document.write(n + " sided convex polygon have " ); document.write(numberOfDiagonals(n) + " diagonals" ); // This code is contributed by Ankita saini </script> |
输出:
5 sided convex polygon have 5 diagonals
本文由 普拉提克·切哈杰 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END