码迷,mamicode.com
首页 > 其他好文 > 详细

51nod 1166 大数开平方(高精度+牛顿迭代法)

时间:2017-07-10 00:39:07      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:public   sub   .com   substring   src   rgs   substr   cin   style   

技术分享

分析:直接用二分还是会T,用更快的牛顿迭代法。把问题转化为求x^2-n=0的根,假设解为x0,当前解为x且x^2-n>0,在(x,x^2-n)处作切线,与x轴交点横坐标为新的x,然后迭代即可,比二分法快,但是貌似只能用在凹函数或凸函数上。。

java水高精度真是666。。。

 1 import java.io.*;
 2 import java.util.*;
 3 import java.math.BigInteger;
 4 public class Main {
 5     public static void main(String[] args){
 6         Scanner cin=new Scanner(System.in);
 7         String a;
 8         a=cin.next();
 9         BigInteger n=new BigInteger(a);
10         if(n.toString().length()%2==0)
11             a=a.substring(0,n.toString().length()/2+1);
12         else
13             a=a.substring(0,(1+ n.toString().length())/2);
14         BigInteger x=new BigInteger(a);
15         BigInteger Two=new BigInteger("2");
16         if(a=="1"){
17             System.out.println(1);
18         }else{
19             while(n.compareTo(x.multiply(x))<0){
20                 x=(x.add(n.divide(x))).divide(Two);
21             }
22             System.out.println(x);
23         }
24         cin.close();
25     }
26 }

 

51nod 1166 大数开平方(高精度+牛顿迭代法)

标签:public   sub   .com   substring   src   rgs   substr   cin   style   

原文地址:http://www.cnblogs.com/7391-KID/p/7143655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!