平方开根 - 牛顿迭代(板子整理)

long long 范围内的开根

int Sqrt(int x) {
    if (x == 0) return 0;
    double last = 0;
    double res = 1;
    while (res != last)
    {
        last = res;
        res = (res + x / res) / 2;
    }
    return int(res);
}

 浮点数的开根

double fun(double x) {
    if (x == 0) return 0;
    double last = 0.0;
    double res = 1.0;
    while (res != last)
    {
        last = res;
        res = (res + x / res) / 2;
    }
    return res;
}

 

java 大数套牛顿迭代

import java.math.BigInteger;
import java.math.*;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.*; 
public class Main
{
    public static void bigSqrt(){
         Scanner cin=new Scanner(System.in);
          String s=cin.next();
          BigInteger remain=BigInteger.ZERO;
          BigInteger odd=BigInteger.ZERO;
          BigInteger ans=BigInteger.ZERO;
//          remain=BigInteger.ZERO;
//          odd=BigInteger.ZERO;
//          ans=BigInteger.ZERO;
          int group=0,k=0;
          if(s.length()%2==1)
          {
                  group=s.charAt(0)-'0';
                  k=-1;
          }
          else
          {
                  group=(s.charAt(0)-'0')*10+s.charAt(1)-'0';
                  k=0;
          }
          for(int j=0;j<(s.length()+1)/2;j++)
          {
                  if(j!=0)
                  group=(s.charAt(j*2+k)-'0')*10+s.charAt(j*2+k+1)-'0';
                  odd=BigInteger.valueOf(20).multiply(ans).add(BigInteger.ONE);
                  remain=BigInteger.valueOf(100).multiply(remain).add(BigInteger.valueOf(group));
                  int count=0;
                  while(remain.compareTo(odd)>=0)
                  {
                         count++;
                         remain=remain.subtract(odd);
                         odd=odd.add(BigInteger.valueOf(2));
                  }
                  ans=ans.multiply(BigInteger.TEN).add(BigInteger.valueOf(count));
          }
          System.out.println(ans);
        cin.close();
        return;
    }
       public static void main(String[] args) 
       {
               Scanner cin=new Scanner(System.in);
               //int t=cin.nextInt();

                   bigSqrt();

              cin.close();
      }
}

 

posted @ 2018-09-15 19:53  楼主好菜啊  阅读(403)  评论(0编辑  收藏  举报