Quantcast
Channel: How to check if a number is a power of 2 - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by RARE Kpop Manifesto for How to check if a number is a power of 2

$
0
0

Apparently if you wanna use something other than bit-masking, one can also efficiently determine a power of 2 as a side feature of the Fermat primality test

jot 1048576 | gawk -Mbe '($++NF = 2^((n = +$1) - 1) % n )_' | mawk '/ 0$/'

 1        1 0 2        2 0 3        4 0 4        8 0 5       16 0 6       32 0 7       64 0 8      128 0 9      256 010      512 011     1024 012     2048 013     4096 014     8192 015    16384 016    32768 017    65536 018   131072 019   262144 020   524288 021  1048576 0

The base-2 version of that primality test is checking for the existence of the following congruence :

2^(n - 1) ≡ 1 (mod n)

But a side bonus of the test is that one can also check against a congruence of

2^(n - 1) ≡ 0 (mod n)-

ONLY integer powers of 2 have a zero congruence.


Viewing all articles
Browse latest Browse all 38

Latest Images

Trending Articles



Latest Images