Encontrar si un número dado es una potencia de 4 o no

Dado un entero n, encuentra si es una potencia de 4 o no.

Ejemplo : 

Input : 16
Output : 16 is a power of 4

Input : 20
Output : 20 is not a power of 4

Le recomendamos encarecidamente que haga clic aquí y lo practique antes de pasar a la solución.

1. Usando el método de registro incorporado:

Lleve el logaritmo del número dado a la base 4 y luego eleve 4 a este resultado. Si la salida es igual a n, entonces el número dado es una potencia de 4, de lo contrario no.

C++

// C++ program to find whether a given
// number is a power of 4 or not
#include<bits/stdc++.h>
 
using namespace std;
#define bool int
 
class GFG
{
     
/* Function to check if x is power of 4*/
public : bool isPowerOfFour(int n)
{
    if(n == pow(4, (log(n)/log(4))))
        return true;
    return false;
}
};
 
/*Driver code*/
int main()
{
    GFG g;
    int test_no = 64;
    if(g.isPowerOfFour(test_no))
        cout << test_no << " is a power of 4";
    else
        cout << test_no << " is not a power of 4";
}
 
// This code is contributed by Code_r

Java

// Java program to find whether a given number is a power of
// 4 or not
 
import java.io.*;
 
class GFG {
 
    // Function to check if x is a power of 4
    public boolean isPowerOfFour(int n)
    {
        if (n== (int)Math.pow(4, (Math.log(n) / Math.log(4)))) {
            return true;
        }
        return false;
    }
 
    public static void main(String[] args)
    {
        GFG g = new GFG();
        int test_no = 64;
        if (g.isPowerOfFour(test_no)) {
            System.out.print(test_no + " is a power of 4 ");
        }
        else {
            System.out.print(test_no
                             + " is not a power of 4");
        }
    }
}
 
// This code is contributed by lokesh (lokeshmvs21).

C#

// C# program to find whether a given number is a power of 4
// or not.
 
using System;
 
public class GFG {
 
    // Function to check if x is power of 4
    public bool isPowerOfFour(int n)
    {
        if (n == Math.Pow(4, (Math.Log(n) / Math.Log(4)))) {
            return true;
        }
        return false;
    }
 
    static public void Main()
    {
 
        // Code
        GFG g = new GFG();
        int test_no = 64;
        if (g.isPowerOfFour(test_no)) {
            Console.Write(test_no + " is a power of 4");
        }
        else {
            Console.Write(test_no + " is not a power of 4");
        }
    }
}
 
// This code is contributed by lokesh (lokeshmvs21)

Python3

# Python program to find whether a given number is a power of 4 or not.
 
import math
 
 
# Function to check if x is power of 4
def isPowerOfFour(n):
    if (n == pow(4, (math.log(n)/math.log(4)))):
        return True
    return False
 
 
test_no = 64
if(isPowerOfFour(test_no)):
    print(test_no, ' is a power of 4')
else:
    print(test_no, ' is not a power of 4')
 
 
# This code is contributed by lokesh (lokeshmvs21).
Producción

64 is a power of 4

2. Otra solución es seguir dividiendo el número por 4, es decir, hacer n = n/4 iterativamente. En cualquier iteración, si n%4 se vuelve distinto de cero y n no es 1, entonces n no es una potencia de 4, de lo contrario, n es una potencia de 4. 

C++

// C++ program to find whether a given
// number is a power of 4 or not
#include<iostream>
 
using namespace std;
#define bool int
 
class GFG
{
     
/* Function to check if x is power of 4*/
public : bool isPowerOfFour(int n)
{
    if(n == 0)
        return 0;
    while(n != 1)
    {
        if(n % 4 != 0)
            return 0;
        n = n / 4;
    }
    return 1;
}
};
 
/*Driver code*/
int main()
{
    GFG g;
    int test_no = 64;
    if(g.isPowerOfFour(test_no))
        cout << test_no << " is a power of 4";
    else
        cout << test_no << "is not a power of 4";
    getchar();
}
 
// This code is contributed by SoM15242

C

#include<stdio.h>
#define bool int
 
/* Function to check if x is power of 4*/
bool isPowerOfFour(int n)
{
  if(n == 0)
    return 0;
  while(n != 1)
  {   
   if(n % 4 != 0)
      return 0;
    n = n / 4;     
  }
  return 1;
}
 
/*Driver program to test above function*/
int main()
{
  int test_no = 64;
  if(isPowerOfFour(test_no))
    printf("%d is a power of 4", test_no);
  else
    printf("%d is not a power of 4", test_no);
  getchar();
}

Java

// Java code to check if given
// number is power of 4 or not
 
class GFG {
 
    // Function to check if
    // x is power of 4
    static int isPowerOfFour(int n)
    {
        if(n == 0)
        return 0;
        while(n != 1)
        {
            if(n % 4 != 0)
            return 0;
            n = n / 4;    
        }
        return 1;
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int test_no = 64;
        if(isPowerOfFour(test_no) == 1)
         System.out.println(test_no +
                           " is a power of 4");
        else
         System.out.println(test_no +
                           "is not a power of 4");
    }
}
 
// This code is contributed
// by  prerna saini

Python3

# Python3 program to check if given
# number is power of 4 or not
 
# Function to check if x is power of 4
def isPowerOfFour(n):
    if (n == 0):
        return False
    while (n != 1):
            if (n % 4 != 0):
                return False
            n = n // 4
             
    return True
 
# Driver code
test_no = 64
if(isPowerOfFour(64)):
    print(test_no, 'is a power of 4')
else:
    print(test_no, 'is not a power of 4')
 
# This code is contributed by Danish Raza

C#

// C# code to check if given
// number is power of 4 or not
using System;
 
class GFG {
     
    // Function to check if
    // x is power of 4
    static int isPowerOfFour(int n)
    {
        if (n == 0)
            return 0;
        while (n != 1) {
            if (n % 4 != 0)
                return 0;
            n = n / 4;
        }
        return 1;
    }
 
    // Driver code
    public static void Main()
    {
        int test_no = 64;
        if (isPowerOfFour(test_no) == 1)
            Console.Write(test_no +
                    " is a power of 4");
        else
            Console.Write(test_no +
                " is not a power of 4");
    }
}
 
// This code is contributed by Sam007

PHP

<?php
// PHP code to check if given
// number is power of 4 or not
 
// Function to check if
// x is power of 4
function isPowerOfFour($n)
{
     
    if($n == 0)
        return 0;
    while($n != 1)
    {
        if($n % 4 != 0)
            return 0;
            $n = $n / 4;    
    }
    return 1;
}
 
// Driver Code
$test_no = 64;
 
if(isPowerOfFour($test_no))
    echo $test_no," is a power of 4";
else
    echo $test_no," is not a power of 4";
 
// This code is contributed by Rajesh
?>

Javascript

<script>
 
/* Function to check if x is power of 4*/
function isPowerOfFour( n)
{
  if(n == 0)
    return false;
  while(n != 1)
  {   
   if(n % 4 != 0)
      return false;
    n = n / 4;     
  }
  return true;
}
 
/*Driver program to test above function*/
let test_no = 64;
  if(isPowerOfFour(test_no))
    document.write(test_no+" is a power of 4");
  else
    document.write(test_no+" is not a power of 4");
 
// This code is contributed by gauravrajput1
 
</script>
Producción

64 is a power of 4

Complejidad de tiempo: O (log 4 n)

Espacio auxiliar: O(1)
3. Un número n es una potencia de 4 si se cumplen las siguientes condiciones. 
a) Solo hay un bit establecido en la representación binaria de n (o n es una potencia de 2) 
b) La cuenta de bits cero antes de que el (único) bit establecido sea par.
Por ejemplo, 16 (10000) es la potencia de 4 porque solo hay un bit establecido y un conteo de 0 antes de que el bit establecido sea 4, que es par.
Gracias a Geek4u por sugerir el enfoque y proporcionar el código. 

C++

// C++ program to check
// if given number is
// power of 4 or not
#include<bits/stdc++.h>
 
using namespace std;
 
bool isPowerOfFour(unsigned int n)
{
    int count = 0;
 
    /*Check if there is only one bit set in n*/
    if ( n && !(n&(n-1)) )
    {
        /* count 0 bits before set bit */
        while(n > 1)
        {
            n >>= 1;
            count += 1;
        }
 
        /*If count is even then
        return true else false*/
        return (count%2 == 0)? 1 :0;
    }
 
    /* If there are more than 1 bit set
    then n is not a power of 4*/
    return 0;
}
 
/*Driver code*/
int main()
{
    int test_no = 64;
    if(isPowerOfFour(test_no))
        cout << test_no << " is a power of 4" ;
    else
        cout << test_no << " is not a power of 4";
}
 
// This code is contributed by Shivi_Aggarwal

C

#include<stdio.h>
#define bool int
 
bool isPowerOfFour(unsigned int n)
{
  int count = 0;
 
  /*Check if there is only one bit set in n*/
  if ( n && !(n&(n-1)) )
  {
     /* count 0 bits before set bit */
     while(n > 1)
     {
       n  >>= 1;
       count += 1;
     }     
 
    /*If count is even then return true else false*/
    return (count%2 == 0)? 1 :0;
  }
 
  /* If there are more than 1 bit set
    then n is not a power of 4*/
  return 0;
}   
 
/*Driver program to test above function*/
int main()
{
   int test_no = 64;
   if(isPowerOfFour(test_no))
     printf("%d is a power of 4", test_no);
   else
     printf("%d is not a power of 4", test_no);
   getchar();
}

Java

// Java program to check
// if given number is
// power of 4 or not
import java.io.*;
class GFG
{
    static int isPowerOfFour(int n)
    {
        int count = 0;
         
        /*Check if there is
        only one bit set in n*/
        int x = n & (n - 1);
         
        if ( n > 0 && x == 0)
        {
            /* count 0 bits
            before set bit */
            while(n > 1)
            {
                n >>= 1;
                count += 1;
            }
         
            /*If count is even
            then return true
            else false*/
            return (count % 2 == 0) ? 1 : 0;
        }
         
            /* If there are more than
            1 bit set then n is not a
            power of 4*/
        return 0;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int test_no = 64;
         
        if(isPowerOfFour(test_no)>0)
            System.out.println(test_no +
                               " is a power of 4");
        else
            System.out.println(test_no +
                               " is not a power of 4");
    }
}
 
// This code is contributed by mits

Python3

# Python3 program to check if given
# number is power of 4 or not
 
# Function to check if x is power of 4
def isPowerOfFour(n):
     
    count = 0
     
    # Check if there is only one
    # bit set in n
    if (n and (not(n & (n - 1)))):
         
        # count 0 bits before set bit
        while(n > 1):
            n >>= 1
            count += 1
         
        # If count is even then return
        # true else false
        if(count % 2 == 0):
            return True
        else:
            return False
 
# Driver code
test_no = 64
if(isPowerOfFour(64)):
    print(test_no, 'is a power of 4')
else:
    print(test_no, 'is not a power of 4')
 
# This code is contributed by Danish Raza

C#

// C# program to check if given
// number is power of 4 or not
using System;
 
class GFG {
     
    static int isPowerOfFour(int n)
    {
        int count = 0;
         
        /*Check if there is only one bit
        set in n*/
        int x = n & (n-1);
         
        if ( n > 0 && x == 0)
        {
            /* count 0 bits before set bit */
            while(n > 1)
            {
                n >>= 1;
                count += 1;
            }
         
            /*If count is even then return
            true else false*/
            return (count % 2 == 0) ? 1 : 0;
        }
         
            /* If there are more than 1 bit set
            then n is not a power of 4*/
        return 0;
    }
 
    /*Driver program to test above function*/
    static void Main()
    {
        int test_no = 64;
         
        if(isPowerOfFour(test_no)>0)
            Console.WriteLine("{0} is a power of 4",
                                          test_no);
        else
            Console.WriteLine("{0} is not a power of 4",
                                             test_no);
    }
}
 
// This Code is Contributed by mits

PHP

<?php
 
function isPowerOfFour($n)
{
    $count = 0;
 
/*Check if there is only one bit set in n*/
if ( $n && !($n&($n-1)) )
{
    /* count 0 bits before set bit */
    while($n > 1)
    {
    $n >>= 1;
    $count += 1;
    }    
 
    /*If count is even then return true else false*/
    return ($count%2 == 0)? 1 :0;
}
 
/* If there are more than 1 bit set
    then n is not a power of 4*/
return 0;
}
 
/*Driver program to test above function*/
 
    $test_no = 64;
     
if(isPowerOfFour($test_no))
 
    echo $test_no, " is a power of 4";
 
else
 
    echo $test_no, " not is a power of 4";
     
 
#This Code is Contributed by Ajit
?>

Javascript

<script>
 
// javascript program to check
// if given number is
// power of 4 or not
 
function isPowerOfFour( n)
{
    let count = 0;
 
    /*Check if there is only one bit set in n*/
    if ( n && !(n&(n-1)) )
    {
        /* count 0 bits before set bit */
        while(n > 1)
        {
            n >>= 1;
            count += 1;
        }
 
        /*If count is even then
        return true else false*/
        return (count%2 == 0)? 1 :0;
    }
 
    /* If there are more than 1 bit set
    then n is not a power of 4*/
    return 0;
}
 
/*Driver code*/
    let test_no = 64;
    if(isPowerOfFour(test_no))
       document.write( test_no +" is a power of 4" );
    else
        document.write(test_no + " is not a power of 4");
 
 
// This code contributed by aashish1995
 
</script>
Producción

64 is a power of 4

Complejidad de tiempo: O (log 4 n)

Espacio Auxiliar: O(1)

4. Un número n es una potencia de 4 si se cumplen las siguientes condiciones. 
a) Solo hay un bit establecido en la representación binaria de n (o n es una potencia de 2) 
b) Los bits no AND(&) ninguna parte del patrón 0xAAAAAAAA
Por ejemplo: 16 (10000) es una potencia de 4 porque solo hay un bit establecido y 0x10 y 0xAAAAAAAA es cero.
Gracias a Sarthak Sahu por sugerir el enfoque. 

C++

// C++ program to check
// if given number is
// power of 4 or not
#include<bits/stdc++.h>
 
using namespace std;
 
bool isPowerOfFour(unsigned int n)
{
    return n !=0 && ((n&(n-1)) == 0) && !(n & 0xAAAAAAAA);
}
 
/*Driver code*/
int main()
{
    int test_no = 64;
    if(isPowerOfFour(test_no))
        cout << test_no << " is a power of 4" ;
    else
        cout << test_no << " is not a power of 4";
}

C

// C program to check
// if given number is
// power of 4 or not
#include<stdio.h>
#define bool int
 
bool isPowerOfFour(unsigned int n)
{
  return n != 0 && ((n&(n-1)) == 0) && !(n & 0xAAAAAAAA);
}   
 
/*Driver program to test above function*/
int main() {
   int test_no = 64;
   if(isPowerOfFour(test_no))
     printf("%d is a power of 4", test_no);
   else
     printf("%d is not a power of 4", test_no);
   getchar();
}

Java

// Java program to check
// if given number is
// power of 4 or not
import java.io.*;
class GFG {
    static boolean isPowerOfFour(int n) {
        return n != 0 && ((n&(n-1)) == 0) && (n & 0xAAAAAAAA) == 0;
    }
 
    // Driver Code
    public static void main(String[] args) {
        int test_no = 64;
         
        if(isPowerOfFour(test_no))
            System.out.println(test_no +
                               " is a power of 4");
        else
            System.out.println(test_no +
                               " is not a power of 4");
    }
}

Python3

# Python3 program to check
# if given number is
# power of 4 or not
def isPowerOfFour(n):
    return (n != 0 and
          ((n & (n - 1)) == 0) and
            not(n & 0xAAAAAAAA));
 
# Driver code
test_no = 64;
if(isPowerOfFour(test_no)):
    print(test_no ,"is a power of 4");
else:
    print(test_no , "is not a power of 4");
 
# This code contributed by Rajput-Ji

C#

// C# program to check
// if given number is
// power of 4 or not
using System;
 
class GFG
{
    static bool isPowerOfFour(int n)
    {
        return n != 0 && ((n&(n-1)) == 0) &&
                        (n & 0xAAAAAAAA) == 0;
    }
 
    // Driver Code
    static void Main()
    {
        int test_no = 64;
         
        if(isPowerOfFour(test_no))
            Console.WriteLine("{0} is a power of 4",
                                        test_no);
        else
            Console.WriteLine("{0} is not a power of 4",
                                            test_no);
    }
}
 
// This code is contributed by mohit kumar 29

Javascript

<script>
// C++ program to check
// if given number is
// power of 4 or not
 
  
function isPowerOfFour( n)
{
    return n !=0 && ((n&(n-1)) == 0) && !(n & 0xAAAAAAAA);
}
  
/*Driver code*/
 test_no = 64;
    if(isPowerOfFour(test_no))
        document.write(test_no + " is a power of 4");
    else
        document.write(test_no + " is not a power of 4");
//This code is contributed by simranarora5sos
</script>
Producción

64 is a power of 4

Complejidad de tiempo: O (log 4 n)

Espacio auxiliar: O(1)
¿Por qué 0xAAAAAAAA? Esto se debe a que la representación de bits es de potencias de 2 que no son de 4. Como 2, 8, 32, etc.
5. Un número será una potencia de 4 si floor(log4(num))=ceil(log4(num) porque log4 de un número que es una potencia de 4 siempre será un número entero. 

A continuación se muestra la implementación del enfoque anterior. 

C++

// C++ program to check 
// if given number is 
// power of 4 or not 
#include<bits/stdc++.h>
   
using namespace std;
 
float logn(int n, int r)
{
    return log(n) / log(r);
}
 
bool isPowerOfFour(int n)
{
    //0 is not considered as a power
    //of 4
    if(n == 0)
        return false;
    return floor(logn(n,4))==ceil(logn(n,4));
} 
   
/*Driver code*/
int main()
{
    int test_no = 64;
    if(isPowerOfFour(test_no))
        cout << test_no << " is a power of 4" ;
    else
        cout << test_no << " is not a power of 4";
    return 0;
}

Java

// Java program to check
// if given number is
// power of 4 or not
import java.util.*;
class GFG{
 
static double logn(int n,
                   int r)
{
  return Math.log(n) /
         Math.log(r);
}
 
static boolean isPowerOfFour(int n)
{
  // 0 is not considered
  // as a power of 4
  if (n == 0)
    return false;
  return Math.floor(logn(n, 4)) ==
         Math.ceil(logn(n, 4));
}
 
// Driver code
public static void main(String[] args)
{
  int test_no = 64;
  if (isPowerOfFour(test_no))
    System.out.print(test_no +
                     " is a power of 4");
  else
    System.out.print(test_no +
                     " is not a power of 4");
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python3 program to check
# if given number is
# power of 4 or not
import math
 
def logn(n, r):
    return math.log(n) / math.log(r)
 
def isPowerOfFour(n):
     
    # 0 is not considered
    # as a power of 4
    if (n == 0):
        return False
         
    return (math.floor(logn(n, 4)) ==
             math.ceil(logn(n, 4)))
 
# Driver code
if __name__ == '__main__':
     
    test_no = 64
     
    if (isPowerOfFour(test_no)):
        print(test_no, " is a power of 4")
    else:
        print(test_no, " is not a power of 4")
 
# This code is contributed by Amit Katiyar

C#

// C# program to check
// if given number is
// power of 4 or not
using System;
class GFG{
 
static double logn(int n,
                   int r)
{
  return Math.Log(n) /
         Math.Log(r);
}
 
static bool isPowerOfFour(int n)
{
  // 0 is not considered
  // as a power of 4
  if (n == 0)
    return false;
  return Math.Floor(logn(n, 4)) ==
         Math.Ceiling(logn(n, 4));
}
 
// Driver code
public static void Main(String[] args)
{
  int test_no = 64;
  if (isPowerOfFour(test_no))
    Console.Write(test_no +
                  " is a power of 4");
  else
    Console.Write(test_no +
                  " is not a power of 4");
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
// javascript program to check 
// if given number is 
// power of 4 or not 
   
 
function logn( n,  r)
{
    return Math.log(n) / Math.log(r);
}
 
function isPowerOfFour( n)
{
    //0 is not considered as a power
    //of 4
    if(n == 0)
        return false;
    return Math.floor(logn(n,4))==Math.ceil(logn(n,4));
} 
   
/*Driver code*/
 
    let test_no = 64;
    if(isPowerOfFour(test_no))
        document.write(test_no + " is a power of 4") ;
    else
        document.write( test_no + " is not a power of 4");
    
    // This code contributed by gauravrajput1
 
</script>
Producción

64 is a power of 4

Complejidad de tiempo: O (log 4 n)

Espacio Auxiliar: O(1)

6. Usando Log y sin usar ceil (Oneliner)

Podemos calcular fácilmente sin usar ceil comprobando que el logaritmo del número base 4 elevado a 4 es igual a ese número

C++

// C++ program to check
// if given number is
// power of 4 or not
#include <bits/stdc++.h>
using namespace std;
 
int isPowerOfFour(int n)
{
    return (n > 0 and pow(4, int(log2(n) /
                                 log2(4))) == n);
}
 
// Driver code
int main()
{
    int test_no = 64;
 
    if (isPowerOfFour(test_no))
        cout << test_no << " is a power of 4";
    else
        cout << test_no << " is not a power of 4";
         
    return 0;
}
 
// This code is contributed by ukasp

Java

// Java program to check
// if given number is
import java.io.*;
 
class GFG{
     
static boolean isPowerOfFour(int n)
{
    return (n > 0 && Math.pow(
        4, (int)((Math.log(n) /
                  Math.log(2)) /
                 (Math.log(4) /
                  Math.log(2)))) == n);
}
 
// Driver code
public static void main(String[] args)
{
    int test_no = 64;
     
    if (isPowerOfFour(test_no))
        System.out.println(test_no +
         " is a power of 4");
    else
        System.out.println(test_no +
         " is not a power of 4");
}
}
 
// This code is contributed by rag2127

Python3

# Python3 program to check
# if given number is
# power of 4 or not
import math
 
 
def isPowerOfFour(n):
    return (n > 0 and 4**int(math.log(n, 4)) == n)
 
 
# Driver code
if __name__ == '__main__':
 
    test_no = 64
 
    if (isPowerOfFour(test_no)):
        print(test_no, " is a power of 4")
    else:
        print(test_no, " is not a power of 4")
 
# This code is contributed by vikkycirus

C#

// C# program to check
// if given number is
using System;
class GFG
{
     
static Boolean isPowerOfFour(int n)
{
    return (n > 0 && Math.Pow(
        4, (int)((Math.Log(n) /
                  Math.Log(2)) /
                 (Math.Log(4) /
                  Math.Log(2)))) == n);
}
 
// Driver code
public static void Main(String[] args)
{
    int test_no = 64;
     
    if (isPowerOfFour(test_no))
        Console.WriteLine(test_no +
         " is a power of 4");
    else
        Console.WriteLine(test_no +
         " is not a power of 4");
}
}
 
// This code is contributed by shivanisinghss2110

Javascript

<script>
 
// Javascript program to check
// if given number is
// power of 4 or not
function isPowerOfFour(n)
{
    return (n > 0 && Math.pow(4, (Math.log2(n) /
                                 Math.log2(4)) == n));
}
         
// Driver code
let test_no = 64;
 
if (isPowerOfFour(test_no))
    document.write(test_no +
                   " is a power of 4");
else
    document.write(test_no +
                   " is not a power of 4");
                    
// This code is contributed by avijitmondal1998
 
</script>
Producción

64 is a power of 4

Complejidad de tiempo: O (log 4 n)

Espacio Auxiliar: O(1)

7. Un número ‘n’ es una potencia de 4 si –

a) es un cuadrado perfecto

b) Es una potencia de dos

A continuación se muestra la implementación de la idea anterior.

C++

// C++ program to check if given number is power of 4 or not
#include <bits/stdc++.h>
using namespace std;
 
// Function to check perfect square
bool isPerfectSqaure(int n)
{
    int x = sqrt(n);
    return (x * x == n);
}
 
bool isPowerOfFour(int n)
{
    // If n <= 0, it is not the power of four
    if (n <= 0)
        return false;
    // Check whether 'n' is a perfect square or not
    if (!isPerfectSqaure(n))
        return false;
 
    // If 'n' is the perfect square Check for the second
    // condition i.e. 'n' must be power of two
    return !(n & (n - 1));
}
 
/*Driver code*/
int main()
{
    int test_no = 64;
    if (isPowerOfFour(test_no))
        cout << test_no << " is a power of 4";
    else
        cout << test_no << " is not a power of 4";
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C

// C program to check if given number is power of 4 or not
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
 
// Function to check perfect square
bool isPerfectSqaure(int n)
{
    int x = sqrt(n);
    return (x * x == n);
}
 
bool isPowerOfFour(int n)
{
    // If n <= 0, it is not the power of four
    if (n <= 0)
        return false;
    // Check whether 'n' is a perfect square or not
    if (!isPerfectSqaure(n))
        return false;
 
    // If 'n' is the perfect square Check for the second
    // condition i.e. 'n' must be power of two
    return !(n & (n - 1));
}
 
/*Driver code*/
int main()
{
    int test_no = 64;
    if (isPowerOfFour(test_no))
        printf("%d is a power of 4", test_no);
    else
        printf("%d is not a power of 4", test_no);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Java program to check
// if given number is
// power of 4 or not
import java.util.*;
 
class GFG {
 
    // Function to check perfect square
    static boolean isPerfectSqaure(int n) {
        int x = (int) Math.sqrt(n);
 
        return (x * x == n);
    }
 
    static boolean isPowerOfFour(int n)
    {
       
        // If n <= 0, it is not the power of four
        if (n <= 0)
            return false;
 
        // Check whether 'n' is a perfect square or not
        if (!isPerfectSqaure(n))
            return false;
 
        // If 'n' is the perfect square
        // Check for the second condition i.e. 'n' must be power of two
        return (n & (n - 1)) != 1 ? true : false;
    }
 
    /* Driver code */
    public static void main(String[] args) {
        int test_no = 64;
        if (isPowerOfFour(test_no))
            System.out.print(test_no + " is a power of 4");
        else
            System.out.print(test_no + " is not a power of 4");
    }
}
 
// This code is contributed by gauravrajput1

Python3

# Python program to check
# if given number is
# power of 4 or not
# Function to check perfect square
# import the math module
import math
 
def isPerfectSqaure(n):
    x = math.sqrt(n)
    return (x*x == n)
 
 
def isPowerOfFour(n):
     
      # If n <= 0, it is not the power of four
      if(n <= 0):
         return False
   
      # Check whether 'n' is a perfect square or not
      if(isPerfectSqaure(n)):
         return False    
     
      # If 'n' is the perfect square
      # Check for the second condition i.e. 'n' must be power of two
      return (n & (n - 1))
  
# Driver code
test_no = 64
if(isPowerOfFour(test_no)):
        print(test_no ," is a power of 4")
else:
        print(test_no ," is not a power of 4")
 
# This code is contributed by shivanisinghss2110

C#

// C# program to check
// if given number is
// power of 4 or not
using System;
 
public class GFG {
 
    // Function to check perfect square
    static bool isPerfectSqaure(int n) {
        int x = (int) Math.Sqrt(n);
 
        return (x * x == n);
    }
 
    static bool isPowerOfFour(int n)
    {
       
        // If n <= 0, it is not the power of four
        if (n <= 0)
            return false;
 
        // Check whether 'n' is a perfect square or not
        if (!isPerfectSqaure(n))
            return false;
 
        // If 'n' is the perfect square
        // Check for the second condition i.e. 'n' must be power of two
        return (n & (n - 1)) != 1 ? true : false;
    }
 
    /* Driver code */
    public static void Main(String[] args) {
        int test_no = 64;
        if (isPowerOfFour(test_no))
            Console.Write(test_no + " is a power of 4");
        else
            Console.Write(test_no + " is not a power of 4");
    }
}
 
// This code is contributed by umadevi9616

Javascript

<script>
 
// JavaScript program to check
// if given number is
// power of 4 or not
// Function to check perfect square
function isPerfectSqaure( n) {
        var x = Math.sqrt(n);
 
        return (x * x == n);
    }
 
function isPowerOfFour(n)
    {
       
        // If n <= 0, it is not the power of four
        if (n <= 0)
            return false;
 
        // Check whether 'n' is a perfect square or not
        if (!isPerfectSqaure(n))
            return false;
 
        // If 'n' is the perfect square
        // Check for the second condition i.e. 'n' must be power of two
        return (n & (n - 1)) != 1 ? true : false;
    }
 
    /* Driver code */
        var test_no = 64;
        if (isPowerOfFour(test_no))
            document.write(test_no + " is a power of 4");
        else
            document.write(test_no + " is not a power of 4");
 
// This code is contributed by shivanisinghss2110
 
</script>
Producción

64 is a power of 4

Complejidad del tiempo: O(log 2 n)

Espacio Auxiliar: O(1)

Escriba comentarios si encuentra que alguno de los códigos/algoritmos anteriores es incorrecto o encuentra otras formas de resolver el mismo problema.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *