-2

It is a simple program to find out if an integer is a power of 4, but I couldn't understand this section when we take integer 255 & 256:

 $x = $n;
              while ($x % 4 == 0) {
              $x /= 4;
             }

            if($x == 1)

Can someone explain it to me?

<?php
    function is_Power_of_four($n)
    {
          $x = $n;
          while ($x % 4 == 0) {
          $x /= 4;
         }

        if($x == 1)
        {
            return "$n is power of 4";
        }
        else
        {
            return "$n is not power of 4";
        }

    }
    print_r(is_Power_of_four(4)."\n");
    print_r(is_Power_of_four(255)."\n");
    print_r(is_Power_of_four(256)."\n");
  ?>
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Legend
  • 422
  • 6
  • 14

1 Answers1

1

It's idiomatic in older languages like C.

A number x greater than 1 that is a power of two will have an binary representation 1 0 ... where ... is any number of zeros.

One less than a number that's a power of two (x - 1, say) will have the binary representation 1 ... where ... is any number of ones. Furthermore it will have one fewer binary digit than x. It's also obvious that a subtraction of one from a power of 2 flips all the bits in that original number: no other number has this property.

& is the bitwise AND operator. Reference http://php.net/manual/en/language.operators.bitwise.php

Hence x & (x - 1) will be 0 if and only if x is an exact power of 2.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Can you be more specific from line 3 ? I didn't understand the line from - "One less than a number That's a ........... power of two (x-1, say) will have....... – Legend Aug 22 '17 at 13:03
  • 1
    E.g. take 16. That is 0b10000. 15 is 0b1111. 0b10000 & 0b1111 is 0. – Bathsheba Aug 22 '17 at 13:29