给定N边的规则多边形,任务是找到可以通过连接不相邻的顶点来刻入给定多边形内的最大边多边形。如果不存在这样的多边形,则打印-1 。
例子:
Input: N = 8
Output: 4
Explanation:
At most a 4 sided polygon can be inscribed inside the given 8-sided polygon as shown below:
Input: N = 3
Output: -1
方法:这个想法是要观察这样一个事实:如果N是偶数,则可以在N个边的另一个正多边形内刻入一个正多边形。请按照以下步骤解决问题:
- 如果N是偶数,则可以通过连接不相邻的顶点来形成具有最大边的内接多边形。因此,打印N / 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)