Search code examples
phppow

Whether given number is a power of any other natural number php?


I tried to find For a given positive integer Z, check if Z can be written as PQ, where P and Q are positive integers greater than 1. If Z can be written as PQ, return 1, else return 0

I tried lots with online solution,

Check if one integer is an integer power of another

Finding if a number is a power of 2

but it's not what i need , any hint or any tips?


Solution

  • Here's the naive method - try every combination:

    function check($z) {
        for($p = 2; $p < sqrt($z); $p++) {
    
            if($z % $p > 0) {
                continue;
            }
    
            $q = $p;
    
            for($i = 1; $q < $z; $i++) {
                $q *= $p;
            }
    
            if($q == $z) {
                //print "$z = $p^$i";
                return 1;
            }
        }
    
        return 0;
    }
    

    Similarly, using php's built in log function. But it may not be as accurate (if there are rounding errors, false positives may occur).

    function check($z) {
        for($p = 2; $p < sqrt($z); $p++) {
            $q = log($z,$p);
            if($q == round($q)) {
                return 1;
            } 
        }
    
        return 0;
    }