w3resource logo


php exercises

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

PHP Challenges - 1: Exercise-2 with Solution

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

Input : 9
Output : 9 is power of 3

Explanation :

PHP: Check if an given positive integer is a power of three

Sample Solution :-

PHP Code :

<?php
function is_Power_of_three($n)
{
      $x = $n;
      while ($x % 3 == 0) {
      $x /= 3;
     }
       
	if($x == 1)
    {
		return "$n is power of 3";
    }
    else
    {
		return "$n is not power of 3";
    }
  
}
print_r(is_Power_of_three(9)."\n");
print_r(is_Power_of_three(81)."\n");
print_r(is_Power_of_three(21)."\n");
?>

Output :

9 is power of 3                                             
81 is power of 3                                            
21 is not power of 3

Flowchart:

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

PHP Code Editor:

<?php
function is_Power_of_three($n)
{
      $x = $n;
      while ($x % 3 == 0) {
      $x /= 3;
     }
       
	if($x == 1)
    {
		return "$n is power of 3";
    }
    else
    {
		return "$n is not power of 3";
    }
  
}
print_r(is_Power_of_three(9)."\n");
print_r(is_Power_of_three(81)."\n");
print_r(is_Power_of_three(21)."\n");
?>

Improve this sample solution and post your code through Disqus



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

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number