current position:Home>How does solidity calculate the square root of a number?

How does solidity calculate the square root of a number?

2022-02-03 20:51:35 Q & A of Denglian community

As the title , In smart contract language If you use Solidity How to get the square root of a number ? Is there any relevant API.




Take the answer 1:

Solidity Support for mathematical formulas is weak , For integers , Support only :

  • Comparison operator : <= , < , == , != , >= , > ( Returns a Boolean value )
  • An operator : & , | , ^ ( Exclusive or ), ~ ( Bit inversion )
  • Shift Operators : << ( Shift left ) , >> ( Shift right )
  • Arithmetic operator : + , - , Unary operation - , Unary operation + , * , / , % ( Remainder or modulo operation ) , ** ( power )

So in Solidity file Can't find the corresponding API.

If you can use the following code :

pragma solidity ^0.4.18;contract  MathSqrt {  function sqrt(uint x) public pure returns(uint) {    uint z = (x + 1 ) / 2;    uint y = x;    while(z &lt; y){      y = z;      z = ( x / z + z ) / 2;    }    return y;  }}

This calculation will be rounded down , namely : 5 The square root of is 2.

If you need to find the square root strictly , You can add a judgment :

    uint b = sqrt(a);    require(b * b == a, " Invalid square root ");



copyright notice
author[Q & A of Denglian community],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202032051330859.html

Random recommended