w3resource logo


php exercises

PHP Challenges: Check if a given positive integer is a power of four

PHP Challenges - 1: Exercise-3 with Solution

Write a PHP program to check if a given positive integer is a power of four.

Input : 4
Output : 4 is power of 4

Explanation :

PHP: Check if a given positive integer is a power of four

Sample Solution :-

PHP Code :

<?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(36)."\n");
print_r(is_Power_of_four(16)."\n");
?>

Output :

4 is power of 4                                             
36 is not power of 4                                        
16 is power of 4

Flowchart:

PHP Flowchart: Check if a given positive integer is a power of four

PHP Code Editor:

<?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(36)."\n");
print_r(is_Power_of_four(16)."\n");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.