Skip to content

Instantly share code, notes, and snippets.

@tounsils
Last active August 10, 2021 13:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tounsils/d13d9efea1964c4f5b0f4c3ca81cf187 to your computer and use it in GitHub Desktop.
Save tounsils/d13d9efea1964c4f5b0f4c3ca81cf187 to your computer and use it in GitHub Desktop.
Write a PHP program to check if a given positive integer is a power of two.
<?php
/**
* Write a PHP program to check if a given positive integer is a power of two.
* Input : 4
*
*
* Example (positive):
* n = 32
* than in binary representation
* n = 100000
* Then n - 1 = 011111 So if you take n - 1 & n you get 0.
* Example (negative):
* n = 6
* than in binary representation
* n = 110
* Now
* n - 1 = 101
* So ((n - 1) & n) == 100 > 0.
*/
function is_Power_of_two($n)
{
if(($n & ($n - 1)) == 0)
{
return "$n is power of 2";
}
else
{
return "$n is not power of 2";
}
}
print_r(is_Power_of_two(4)."\n");
print_r(is_Power_of_two(37)."\n");
print_r(is_Power_of_two(16)."\n");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment