Find the vertex diagonally opposite to the vertex M from an N-sided polygon
Last Updated :
17 Mar, 2021
Given two integers N and M, the task is to find the vertex diagonally opposite to the Mth vertex of an N-sided polygon.
Examples:
Input: N = 6, M = 2
Output: 5
Explanation:
It can be observed from the image above that the vertex opposite to vertex 5 is 2.
Input: N = 8, M = 5
Output: 1
Explanation:
It can be observed from the image above that the vertex opposite to vertex 8 is 1.
Approach: The following two cases need to be considered to solve the given problem:
- If M > N / 2: The vertex will always be M — (N / 2).
- If M ? N / 2: The vertex will always be M + (N / 2).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getPosition( int N, int M)
{
if (M > (N / 2)) {
return (M - (N / 2));
}
return (M + (N / 2));
}
int main()
{
int N = 8, M = 5;
cout << getPosition(N, M);
return 0;
}
|
Java
class GFG{
static int getPosition( int N,
int M)
{
if (M > (N / 2 ))
{
return (M - (N / 2 ));
}
return (M + (N / 2 ));
}
public static void main(String[] args)
{
int N = 8 , M = 5 ;
System.out.print(getPosition(N, M));
}
}
|
Python3
def getPosition(N, M):
if (M > (N / / 2 )):
return (M - (N / / 2 ))
return (M + (N / / 2 ))
N = 8
M = 5
print (getPosition(N, M))
|
C#
using System;
class GFG{
static int getPosition( int N, int M)
{
if (M > (N / 2))
{
return (M - (N / 2));
}
return (M + (N / 2));
}
public static void Main(String[] args)
{
int N = 8, M = 5;
Console.Write(getPosition(N, M));
}
}
|
Javascript
<script>
function getPosition(N, M)
{
if (M > parseInt(N / 2)) {
return (M - parseInt(N / 2));
}
return (M + parseInt(N / 2));
}
var N = 8, M = 5;
document.write(getPosition(N, M));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...