There are n boys and n (n < 10) girls are to be seated around a round table, in a circle. The task is to find the number of ways in which n boys and n girls can sit alternatively around a round table.
Examples:
Input: n = 5
Output: 2880
Input: n = 1
Output: 1
Explanation: There is only 1 boy and 1 girl.
So there is only one possible arrangement
Approach:
- First, find the total number of ways in which boys can be arranged on a round table.
No. of ways to arrange boys on table = (n-1)! - After making boys’ arrangements, now make arrangements for girls. After seating boys, there are n space available between them. So there are n positions and n number of girls.
- So the total number of arrangement in which girls sit between boys are n!.
- Therefore Total number of ways = (number of arrangements of boys) * (number of ways to sit girl among boys) = (n-1)! * (n!)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long int
int main()
{
ll n = 5;
ll fac1 = 1;
for ( int i = 2; i <= n - 1; i++)
fac1 = fac1 * i;
ll fac2 = fac1 * n;
ll totalWays = fac1 * fac2;
cout << totalWays << endl;
return 0;
}
|
Java
import java .io.*;
class GFG
{
public static void main(String[] args)
{
long n = 5 ;
long fac1 = 1 ;
for ( int i = 2 ; i <= n - 1 ; i++)
fac1 = fac1 * i;
long fac2 = fac1 * n;
long totalWays = fac1 * fac2;
System.out.println(totalWays);
}
}
|
Python3
n = 5
fac1 = 1
for i in range ( 2 , n):
fac1 = fac1 * i
fac2 = fac1 * n
totalWays = fac1 * fac2
print (totalWays)
|
C#
using System;
class GFG
{
public static void Main()
{
long n = 5;
long fac1 = 1;
for ( int i = 2; i <= n - 1; i++)
fac1 = fac1 * i;
long fac2 = fac1 * n;
long totalWays = fac1 * fac2;
Console.WriteLine(totalWays);
}
}
|
PHP
<?php
$n = 5;
$fac1 = 1;
for ( $i = 2; $i <= $n - 1; $i ++)
$fac1 = $fac1 * $i ;
$fac2 = $fac1 * $n ;
$totalWays = $fac1 * $fac2 ;
echo $totalWays . "\n" ;
|
Javascript
<script>
let n = 5;
let fac1 = 1;
for (let i = 2; i <= n - 1; i++)
fac1 = fac1 * i;
fac2 = fac1 * n;
totalWays = fac1 * fac2;
document.write(totalWays + "<br>" );
</script>
|
Time complexity: O(n), for iterating over n to calculate factorial.
Auxiliary Space: O(1)