Polygon with maximum sides that can be inscribed in an N-sided regular polygon
Last Updated :
24 Mar, 2021
Given a regular polygon of N sides, the task is to find the maximum sided polygon that can be inscribed inside the given polygon by joining non-adjacent vertices. Print -1, if no such polygon exist.
Examples:
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
Approach: The idea is to observe the fact that a regular polygon can be inscribed inside another regular polygon of N sides if N is even. Follow the below steps to solve the problem:
- If N is even, then the inscribed polygon with the maximum sides can be formed by joining the non-adjacent vertices. Therefore, print N/2 as the required answer.
- Otherwise, print -1 as no regular polygon can be inscribed inside an odd-sided polygon.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int MaximumSides( int n)
{
if (n < 4)
return -1;
return n % 2 == 0 ? n / 2 : -1;
}
int main()
{
int N = 8;
cout << MaximumSides(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int MaximumSides( int n)
{
if (n < 4 )
return - 1 ;
return n % 2 == 0 ?
n / 2 : - 1 ;
}
public static void main(String[] args)
{
int N = 8 ;
System.out.print(MaximumSides(N));
}
}
|
Python3
def MaximumSides(n):
if (n < 4 ):
return - 1
if n % 2 = = 0 :
return n / / 2
return - 1
if __name__ = = '__main__' :
N = 8
print (MaximumSides(N))
|
C#
using System;
class GFG{
static int MaximumSides( int n)
{
if (n < 4)
return -1;
return n % 2 == 0 ?
n / 2 : -1;
}
public static void Main(String[] args)
{
int N = 8;
Console.Write(MaximumSides(N));
}
}
|
Javascript
<script>
function MaximumSides( n)
{
if (n < 4)
return -1;
return n % 2 == 0 ? n / 2 : -1;
}
let N = 8;
document.write(MaximumSides(N));
</script>
|
Output:
4
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...