w3resource

PHP Challenges: Check whether an integer is the power of another integer

PHP Challenges - 1: Exercise-4 with Solution

Write a PHP program to check whether an integer is the power of another integer.

Input : 16, 2

Example: For x = 16 and y = 2 the answer is "true", and for x = 12 and y = 2 "false"

Explanation :

PHP: Check whether an integer is the power of another integer

Sample Solution :

PHP Code :

<?php
// Function to check if $x is a power of $y
function is_Power($x, $y)
{
    // Assign initial values of $x and $y to variables $a and $b respectively
    $a = $x;
    $b = $y;

    // Loop until $x is divisible by $y
    while ($x % $y == 0) {
        // Divide $x by $y
        $x = $x / $y;
    }

    // Check if $x is equal to 1 after the loop
    if ($x == 1) {
        // If true, $a is a power of $b
        return "$a is power of $b";
    } else {
        // If false, $a is not a power of $b
        return "$a is not power of $b";
    }
}

// Testing the function with different inputs
print_r(is_Power(16,2)."\n");
print_r(is_Power(12,2)."\n");
print_r(is_Power(81,3)."\n");
?>

Explanation:

Here is a brief explanation of the above PHP code:

  • The code defines a function named 'is_Power' that checks whether a given number '$x' is a power of another given number '$y'.
  • Inside the function:
    • It assigns the initial values of '$x' and '$y' to variables '$a' and '$b' respectively.
    • It enters a 'while' loop that continues as long as '$x' is divisible by '$y'.
    • Inside the loop, it divides '$x' by '$y' in each iteration.
    • After the loop, it checks if '$x' is equal to 1. If it is, then '$a' is a power of '$b', so it returns a string indicating that. Otherwise, it returns a string indicating that '$a' is not a power of '$b'.
  • The function is tested with different pairs of values '(16,2)', '(12,2)', and '(81,3)' using 'print_r' to display the result of each test.

Sample Output:

16 is power of 2                                            
12 is not power of 2                                        
81 is power of 3

Flowchart:

PHP Flowchart: Check whether an integer is the power of another integer

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check whether a given positive integer is a power of four.
Next: Write a PHP program to find a missing number(s) from an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.