Android Int Overflow Check sqrt(int n)

Here you can find the source of sqrt(int n)

Description

Find the sqrt of a fixed-point value.

License

LGPL

Parameter

Parameter Description
n a parameter

Declaration

public static int sqrt(int n) 

Method Source Code

//package com.java2s;
/*/*from w  ww  .j  ava 2  s . co m*/
 * Taken from android-gl, Making OpenGL Programming in Android Easier
 * URL: https://code.google.com/p/android-gl/source/browse/trunk/AndroidGL/src/edu/union/
 * 
 * License: GNU Lesser General Public License
 * 
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

public class Main {
    /**
     * Find the sqrt of a fixed-point value.
     * 
     * @param n
     * @return
     */
    public static int sqrt(int n) {
        int s = (n + 65536) >> 1;
        for (int i = 0; i < 8; i++) {
            // converge six times
            s = (s + divide(n, s)) >> 1;
        }
        return s;
    }

    /**
     * Divide two fixed-point values.
     * 
     * @param x
     * @param y
     * @return
     */
    public static int divide(int x, int y) {
        long z = (((long) x) << 32);
        return (int) ((z / y) >> 16);
    }
}

Related

  1. mulAndCheck(int x, int y)
  2. stirlingS2(final int n, final int k)
  3. subAndCheck(int x, int y)
  4. multiply(int x, int y)
  5. multiply(int x, int y)
  6. divide(int x, int y)