asmith Posted October 28, 2009 Share Posted October 28, 2009 Hi, I can't find any function in php to give me the first root of a number. Is there any built-in function for it? For example: 81 => 3 9 => 3 64 => 2 256 => 2 I wrote this function to get it, But it seems sqrt always return a float. <?php function getRoot($num) { if (is_int(sqrt($num))) // (strpos(sqrt($num), '.')) $num = sqrt($num); return $num; } ?> Any idea? Quote Link to comment https://forums.phpfreaks.com/topic/179331-solved-first-root-of-a-number/ Share on other sites More sharing options...
asmith Posted October 28, 2009 Author Share Posted October 28, 2009 That's while not if. Quote Link to comment https://forums.phpfreaks.com/topic/179331-solved-first-root-of-a-number/#findComment-946184 Share on other sites More sharing options...
Mark Baker Posted October 28, 2009 Share Posted October 28, 2009 The sqrt() function will always return a float, otherwise it would be a totally useless function for those people who needed to get the square root of 5 or of 19.... in fact it would only be useful for your very specific set of circumstances. $tmp = sqrt($num); if ($tmp == floor($tmp)) { // sqrt($num) is a whole number Note that your function simply won't work. You need a loop to retrieve the first root of a number, and probably want some form of trapping if there isn't a valid whole root for a value. function firstRoot($number) { $nbr = $root = $number; do { $root = sqrt($nbr); if (($root > 1.0) && (floor($root) == $root)) { $nbr = $root; } } while (($root > 1.0) && (floor($root) == $root)) ; if ($number == $nbr) { return false; } return $nbr; } function testRoot($number) { $root = firstRoot($number); if ($root === false) { echo 'There is no first root for '.$number.'<br />'; } else { echo 'The first root of '.$number.' is '.$root.'<br />'; } } $testValues = array(1, 16, 9, 21, 77, 81, 125, 256); foreach ($testValues as $testValue) { testRoot($testValue); } Quote Link to comment https://forums.phpfreaks.com/topic/179331-solved-first-root-of-a-number/#findComment-946219 Share on other sites More sharing options...
asmith Posted October 28, 2009 Author Share Posted October 28, 2009 Thanks for the replay mate I wrote something similar for it. For some reason I thought there MUST be a built-in function for that. Again thanks for your time. Quote Link to comment https://forums.phpfreaks.com/topic/179331-solved-first-root-of-a-number/#findComment-946228 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.