Given an integer M which is the number of matches played in a tournament and each participating team has played a match with all the other teams. The task is to find how many teams are there in the tournament.
Examples:
Input: M = 3
Output: 3
If there are 3 teams A, B and C then
A will play a match with B and C
B will play a match with C (B has already played a match with A)
C has already played matches with team A and B
Total matches played are 3
Input: M = 45
Output: 10
Approach: Since each match is played between two teams. So this problem is similar to selecting 2 objects from Given N objects. Therefore the total number of matches will be C(N, 2), where N is the number of participating teams. Therefore,
M = C(N, 2)
M = (N * (N – 1)) / 2
N2 – N – 2 * M = 0
This is a quadratic equation of type ax2 + bx + c = 0. Here a = 1, b = -1, c = 2 * M. Therefore, applying formula
x = (-b + sqrt(b2 – 4ac)) / 2a and x = (-b – sqrt(b2 – 4ac)) / 2a
N = [(-1 * -1) + sqrt((-1 * -1) – (4 * 1 * (-2 * M)))] / 2
N = (1 + sqrt(1 + (8 * M))) / 2 and N = (1 – sqrt(1 + (8 * M))) / 2
After solving the above two equations, we’ll get two values of N. One value will be positive and one negative. Ignore the negative value. Therefore, the number of teams will be the positive root of the above equation.
Below is the implementation of the above approach:
C++
#include <cmath>
#include <iostream>
using namespace std;
int number_of_teams( int M)
{
int N1, N2, sqr;
sqr = sqrt (1 + (8 * M));
N1 = (1 + sqr) / 2;
N2 = (1 - sqr) / 2;
if (N1 > 0)
return N1;
return N2;
}
int main()
{
int M = 45;
cout << number_of_teams(M);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int number_of_teams( int M)
{
int N1, N2, sqr;
sqr = ( int )Math.sqrt( 1 + ( 8 * M));
N1 = ( 1 + sqr) / 2 ;
N2 = ( 1 - sqr) / 2 ;
if (N1 > 0 )
return N1;
return N2;
}
public static void main (String[] args)
{
int M = 45 ;
System.out.println( number_of_teams(M));
}
}
|
Python3
import math
def number_of_teams(M):
N1, N2, sqr = 0 , 0 , 0
sqr = math.sqrt( 1 + ( 8 * M))
N1 = ( 1 + sqr) / 2
N2 = ( 1 - sqr) / 2
if (N1 > 0 ):
return int (N1)
return int (N2)
def main():
M = 45
print (number_of_teams(M))
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG
{
static int number_of_teams( int M)
{
int N1, N2, sqr;
sqr = ( int )Math.Sqrt(1 + (8 * M));
N1 = (1 + sqr) / 2;
N2 = (1 - sqr) / 2;
if (N1 > 0)
return N1;
return N2;
}
public static void Main()
{
int M = 45;
Console.WriteLine( number_of_teams(M));
}
}
|
PHP
<?php
function number_of_teams( $M )
{
$sqr = sqrt(1 + (8 * $M ));
$N1 = (1 + $sqr ) / 2;
$N2 = (1 - $sqr ) / 2;
if ( $N1 > 0)
return $N1 ;
return $N2 ;
}
$M = 45;
echo number_of_teams( $M );
?>
|
Javascript
<script>
function number_of_teams(M) {
var N1, N2, sqr;
sqr = parseInt( Math.sqrt(1 + (8 * M)));
N1 = (1 + sqr) / 2;
N2 = (1 - sqr) / 2;
if (N1 > 0)
return N1;
return N2;
}
var M = 45;
document.write(number_of_teams(M));
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)