How do you check if a number is a power of 4 in python?

Given a positive number, check if it is a power of four or not.

Practice this problem

Approach 1

A simple solution is to calculate log4n for a given number n. If it returns an integral value, then we can say that the number is a power of four.

This approach is demonstrated below in C++, Java, and Python:

C++


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

#include

#include

usingnamespacestd;

// Returns true if `n` is a power of four

boolcheckPowerOf4[unsignedn]

{

    // find `log4[n]`

    doublei=log[n]/ log[4];

    // return true if `log4[n]` is an integer

    return i==trunc[i];

}

int main[]

{

    unsignedn= 256;

    if[checkPowerOf4[n]]{

        cout

Chủ Đề