📜  可内接在 N 边正多边形中的最大边的多边形

📅  最后修改于: 2021-10-23 08:29:42             🧑  作者: Mango

给定一个N边的正多边形,任务是通过连接不相邻的顶点来找到可以内接在给定多边形内的最大边多边形。如果不存在这样的多边形,则打印-1

例子:

方法:这个想法是观察这样一个事实,如果N是偶数,一个正多边形可以内接在另一个N边的正多边形内。请按照以下步骤解决问题:

  1. 如果N是偶数,则可以通过连接不相邻的顶点来形成具有最大边的内接多边形。因此,打印N/2作为必需的答案。
  2. 否则,打印-1因为没有正多边形可以内接在奇数边多边形内。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum
// sided polygon that can be inscribed
int MaximumSides(int n)
{
    // Base Case
    if (n < 4)
        return -1;
 
    // Return n/2 if n is even
    // Otherwise, return -1
    return n % 2 == 0 ? n / 2 : -1;
}
 
// Driver Code
int main()
{
    // Given N
    int N = 8;
 
    // Function Call
    cout << MaximumSides(N);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Function to find the
// maximum sided polygon
// that can be inscribed
static int MaximumSides(int n)
{
  // Base Case
  if (n < 4)
    return -1;
 
  // Return n/2 if n is
  // even Otherwise, return -1
  return n % 2 == 0 ?
         n / 2 : -1;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given N
  int N = 8;
 
  // Function Call
  System.out.print(MaximumSides(N));
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
 
# Function to find the maximum sided
# polygon that can be inscribed
def MaximumSides(n):
     
    # Base Case
    if (n < 4):
        return -1
 
    # Return n/2 if n is even
    # Otherwise, return -1
    if n % 2 == 0:
        return n // 2
         
    return  -1
 
# Driver Code
if __name__ == '__main__':
     
    # Given N
    N = 8
 
    # Function Call
    print(MaximumSides(N))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
class GFG{
 
// Function to find the
// maximum sided polygon
// that can be inscribed
static int MaximumSides(int n)
{
  // Base Case
  if (n < 4)
    return -1;
 
  // Return n/2 if n is
  // even Otherwise, return -1
  return n % 2 == 0 ?
         n / 2 : -1;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given N
  int N = 8;
 
  // Function Call
  Console.Write(MaximumSides(N));
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:

4

时间复杂度: O(1)
辅助空间: O(1)