Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an integer is a power of 3?

Tags:

algorithm

math

I saw this question, and pop up this idea.

like image 869
Mask Avatar asked Nov 26 '09 15:11

Mask


People also ask

What is an integer power of 3?

In mathematics, a power of three is a number of the form 3n where n is an integer – that is, the result of exponentiation with number three as the base and integer n as the exponent.

How do you check if a number is a power of a number?

A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not.


2 Answers

There exists a constant time (pretty fast) method for integers of limited size (e.g. 32-bit integers).

Note that for an integer N that is a power of 3 the following is true:

  1. For any M <= N that is a power of 3, M divides N.
  2. For any M <= N that is not a power 3, M does not divide N.

The biggest power of 3 that fits into 32 bits is 3486784401 (3^20). This gives the following code:

bool isPower3(std::uint32_t value) {     return value != 0 && 3486784401u % value == 0; } 

Similarly for signed 32 bits it is 1162261467 (3^19):

bool isPower3(std::int32_t value) {     return value > 0 && 1162261467 % value == 0; } 

In general the magic number is:

3^floor(log_3 MAX)== pow(3, floor(log(MAX) / log(3)))

Careful with floating point rounding errors, use a math calculator like Wolfram Alpha to calculate the constant. For example for 2^63-1 (signed int64) both C++ and Java give 4052555153018976256, but the correct value is 4052555153018976267.

like image 155
Elric Avatar answered Nov 16 '22 01:11

Elric


while (n % 3 == 0) {     n /= 3; } return n == 1; 

Note that 1 is the zeroth power of three.

Edit: You also need to check for zero before the loop, as the loop will not terminate for n = 0 (thanks to Bruno Rothgiesser).

like image 45
starblue Avatar answered Nov 16 '22 00:11

starblue