📌  相关文章
📜  从 N 边多边形中找到与顶点 M 对角相对的顶点

📅  最后修改于: 2021-10-25 09:24:08             🧑  作者: Mango

给定两个整数NM ,任务是找到与N 边多边形的M顶点对角相对的顶点。

例子:

方法:解决给定问题需要考虑以下两种情况:

  1. 如果 M > N / 2:顶点将始终为M — (N / 2)
  2. 如果 M ≤ N / 2:顶点将始终为M + (N / 2)

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to return the
// required vertex
int getPosition(int N, int M)
{
 
    // Case 1:
    if (M > (N / 2)) {
        return (M - (N / 2));
    }
 
    // Case 2:
    return (M + (N / 2));
}
 
// Driver Code
int main()
{
    int N = 8, M = 5;
    cout << getPosition(N, M);
 
    return 0;
}


Java
// Java program for
// the above approach
class GFG{
 
// Function to return the
// required vertex
static int getPosition(int N,
                       int M)
{
  // Case 1:
  if (M > (N / 2))
  {
    return (M - (N / 2));
  }
 
  // Case 2:
  return (M + (N / 2));
}
 
// Driver Code
public static void main(String[] args)
{
  int N = 8, M = 5;
  System.out.print(getPosition(N, M));
 
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the
# above approach
 
# Function to return the
# required vertex
def getPosition(N, M):
     
  # Case 1:
  if (M > (N // 2)):
    return (M - (N // 2))
    
  # Case 2:
  return (M + (N // 2))
   
# Driver Code
N = 8
M = 5
 
print(getPosition(N, M))
 
# This code is contributed by code_hunt


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to return the
// required vertex
static int getPosition(int N, int M)
{
     
    // Case 1:
    if (M > (N / 2))
    {
        return (M - (N / 2));
    }
     
    // Case 2:
    return (M + (N / 2));
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 8, M = 5;
     
    Console.Write(getPosition(N, M));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
1

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程