0

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?

2
  • you want to loop 1 through infinity to test? Commented Oct 26, 2015 at 20:19
  • Here's condition , 1<= Z >= 10^9 Commented Oct 26, 2015 at 20:24

1 Answer 1

1

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.