You have to use math calculation logic to get Square root JavaScript without math. Take xi (x
) and the new value of xi + 1 (x1
) and check if the values are equal. Then end the series and return that value.
For starting, you need an appropriate value like half of the given value.
function sqrt(a) {
var x,
x1 = a / 2;
do {
x = x1;
x1 = (x + (a / x)) / 2;
} while (x !== x1);
return x;
}
Source: stackoverflow.com
Example Square root JavaScript without math
Simple example code using while loop to get Square root.
<!DOCTYPE html>
<html>
<head>
<script>
function sqrt(a) {
var x,
x1 = a / 2;
do {
x = x1;
x1 = (x + (a / x)) / 2;
} while (x !== x1);
return x;
}
console.log(sqrt (2));
console.log(sqrt (9));
console.log(sqrt (25));
</script>
</head>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS square root topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version