Find that the value of 2^{2n} is equal to O(2^n) or not
Last Updated :
06 Apr, 2023
Given an integer n, the task is to find that the value of 2^{2n} is equal to O(2^n) or not.
Examples:
Input: n = 2
Output: True
Input: n = 3
Output: False
Proof for the above equation:
We say that f(x) = O(g(x)) if and only if there exist positive constants c and k such that |f(x)| ≤ c|g(x)| for all x ≥ k. So, We need to find constants c and n0 such that |2^{2n}| ≤ c|2^n| for all n > n0.
- Using the properties of exponents, we can rewrite 2^{2n} as (2^n)^2. So we have: ^{2n}| = |(2^n)^2| = (2^n)^2
- Similarly, we can write 2^n as 2*2^{n-1}, so we have: |2^n| = |2*2^{n-1}| = 2|2^{n-1}|
- Substituting these expressions into the inequality above, we get (2^n)^2 ≤ c * 2|2^{n-1}|
- Simplifying the right-hand side, we get: (2^n)^2 ≤ 2c * (2^n)
- Dividing both sides by (2^n), we get: 2^n ≤ 2c
So if we take c = 1, then we have 2^n ≤ 2, or equivalently, n ≥ 1. Therefore, we can conclude that 2^{2n} = O(2^n) with c = 1 and n0 = 1.
Steps involved in the implementation of the code:
- We calculate the values of 2^{n} and 2^{2n} using the pow() function from the cmath library.
- Finally, we check if 2^{2n} is upper-bounded by 2^{n} by comparing the two values.
- If 2^{2n} is indeed upper-bounded by 2^{n}, we print the message “True“.
- Otherwise, we print the message “False“.
Below is the implementation of the above approach:
C++
#include <cmath>
#include <iostream>
using namespace std;
void check( int n)
{
int power_n = pow (2, n);
int power_2n = pow (2, 2 * n);
if (power_2n <= 4 * power_n)
cout << "True" << endl;
else
cout << "False" << endl;
}
int main()
{
int n = 2;
check(n);
return 0;
}
|
Java
import java.lang.Math;
public class GFG {
public static void check( int n)
{
int power_n = ( int )Math.pow( 2 , n);
int power_2n = ( int )Math.pow( 2 , 2 * n);
if (power_2n <= 4 * power_n)
System.out.println( "True" );
else
System.out.println( "False" );
}
public static void main(String[] args)
{
int n = 2 ;
check(n);
}
}
|
Python3
import math
def check(n):
power_n = 2 * * n
power_2n = 2 * * ( 2 * n)
if power_2n < = 4 * power_n:
print ( "True" )
else :
print ( "False" )
if __name__ = = "__main__" :
n = 2
check(n)
|
C#
using System;
class Program {
static void check( int n)
{
int power_n = ( int )Math.Pow(2, n);
int power_2n = ( int )Math.Pow(2, 2 * n);
if (power_2n <= 4 * power_n)
Console.WriteLine( "True" );
else
Console.WriteLine( "False" );
}
static void Main( string [] args)
{
int n = 2;
check(n);
}
}
|
Javascript
function check(n) {
let power_n = Math.pow(2, n);
let power_2n = Math.pow(2, 2 * n);
if (power_2n <= 4 * power_n) {
console.log( "True" );
}
else {
console.log( "False" );
}
}
let n = 2;
check(n);
|
Time Complexity: O(logn), for pow function.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...