Calculate the integer portion of the square root of a positive integer (j2s)

Source: Internet
Author: User

You cannot use floating point numbers in midp1.0.AlgorithmOnly the integer part of a positive integer can be calculated. There is no multiplication or division operation in the algorithm, and only addition or subtraction is required.

Algorithm principle:
1 + 3 + 5 +... + (2n-1) = n ^ 2
According to the formula we ask for the square of X, just let the X-1, X-3, X-5... Until X is negative, then all the successful times are the integer part of the square root.

/**
* @ Todo calculate the integer part of the square root of a positive integer
* @ Param X: a positive integer that requires the square root.
* @ Return integer part of the square root
**/
Private int SQRT (int x)
{
Int result = 0, j = 3;
X --;
While (x> = 0)
{
X-= J;
J + = 2;
Result ++;
}
Return result;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.