Jump to content

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/179331-solved-first-root-of-a-number/
Share on other sites

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);
}


This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.