# C++ Program to find opponent in a circular standing of persons

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have three numbers a, b and c. There are k numbers of students (k is even) standing on a circle, they are numbered from 1 to k in clockwise order. We do not know the value of k. Each person is watching through the center of the circle and can see the opponent who is standing at the other side of the circle. The person with the number 'a' is looking at the person with the number 'b'. We have to find, which person is at the opposite side of the person with number 'c'. If we cannot find this, return -1.

## Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can. This problem we can solve by some mathematical logics. Follow the following contents to understand the approach better.

So, if the input of our problem is like a = 6; b = 2; c = 4, then the output will be 8, because the circle has 8 students. The student with the number 6 will look at the number 2 and the student with the number 8 will look at the student with the number 4.

## Steps

To solve this, we will follow these steps −

n := |a - b|
if a > n or b > n or c > n, then:
return -1
Otherwise
return (n / 2 + c - 1) mod n + 1

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int a, int b, int c){
int n = abs(a - b) * 2;
if (a > n || b > n || c > n)
return -1;
else
return (n / 2 + c - 1) % n + 1;
}
int main(){
int a = 6;
int b = 2;
int c = 4;
cout << solve(a, b, c) << endl;
}

## Input

6, 2, 4

## Output

8
Updated on 08-Apr-2022 07:54:41