Count of distinct graphs that can be formed with N vertices
Given an integer N which is the number of vertices. The task is to find the number of distinct graphs that can be formed. Since the answer can be very large, print the answer % 1000000007.
Examples:
Input: N = 3
Output: 8
Input: N = 4
Output: 64
Approach:
- The maximum number of edges a graph with N vertices can contain is X = N * (N – 1) / 2.
- The total number of graphs containing 0 edge and N vertices will be XC0
- The total number of graphs containing 1 edge and N vertices will be XC1
- And so on from a number of edges 1 to X with N vertices
- Hence, the total number of graphs that can be formed with n vertices will be:
XC0 + XC1 + XC2 + … + XCX = 2X.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
long long power( long long x,
long long y,
const int & MOD)
{
long long res = 1;
while (y > 0) {
if (y & 1)
res = (res * x) % MOD;
x = (x * x) % MOD;
y /= 2;
}
return res;
}
long long countGraphs( int n)
{
long long x = n * (n - 1) / 2;
return power(2, x, MOD);
}
int main()
{
int n = 5;
cout << countGraphs(n);
return 0;
}
|
Java
class GFG
{
static final int MOD = ( int )1e9 + 7 ;
static long power( long x,
long y)
{
long res = 1 ;
while (y > 0 )
{
if ((y & 1 ) != 0 )
res = (res * x) % MOD;
x = (x * x) % MOD;
y /= 2 ;
}
return res;
}
static long countGraphs( int n)
{
long x = n * (n - 1 ) / 2 ;
return power( 2 , x);
}
public static void main (String[] args)
{
int n = 5 ;
System.out.println(countGraphs(n));
}
}
|
Python
MOD = int ( 1e9 + 7 )
def countGraphs(n):
x = (n * ( n - 1 )) / / 2
return ( pow ( 2 , x, MOD))
n = 5
print (countGraphs(n))
|
C#
using System;
class GFG
{
static int MOD = ( int )1e9 + 7;
static long power( long x, long y)
{
long res = 1;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % MOD;
x = (x * x) % MOD;
y /= 2;
}
return res;
}
static long countGraphs( int n)
{
long x = n * (n - 1) / 2;
return power(2, x);
}
static public void Main ()
{
int n = 5;
Console.Write(countGraphs(n));
}
}
|
Javascript
<script>
const MOD = 1000000000 + 7;
function power(x, y, MOD)
{
let res = 1;
while (y > 0) {
if (y & 1)
res = (res * x) % MOD;
x = (x * x) % MOD;
y = parseInt(y / 2);
}
return res;
}
function countGraphs(n)
{
let x = parseInt(n * (n - 1) / 2);
return power(2, x, MOD);
}
let n = 5;
document.write(countGraphs(n));
</script>
|
Time Complexity: O(log(n2))
Auxiliary Space: O(1)
Last Updated :
28 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...