Jump to content

[SOLVED] First root of a number


asmith

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


Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.