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

# 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

Explanation :

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");
?>
```
```

Sample Output:

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

Flowchart:

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