首页 > 其他 > 详细

URAL 1153. Supercomputer 二分求根

时间:2015-03-23 23:57:26      阅读:453      评论:0      收藏:0      [点我收藏+]

1153. Supercomputer

Time limit: 2.0 second
Memory limit: 64 MB
To check the speed of JCN Corporation new supercomputer it was decided to figure out the sum of first N (N < 10600) positive integers. Unfortunately, by the time the calculation was finished the Chief Programmer forgot the value of N he entered. Your task is to write the program (for personal computer), which would determine the value of N by the result calculated on supercomputer.
Note: JCN Corporation manufactures only reliable computers, and its programmers write only correctly working programs.

Input

One line containing the result of calculations on the supercomputer.

Output

Выведите N, the number entered by Chief Programmer.

Sample

input output
28
7
Problem Author: Eugene Bryzgalov 
Problem Source: Ural Collegiate Programming Contest, April 2001, Perm, English Round 


题意

给你1-n个数的和,求出n多大。


做法:

根据等差数列公式, 得 (1+n)*n/2 =(n^2+n)/2;

设给的和 为ans。

n^2+n-2ans=0

然后根据 公式 (-b+根号(b^2-4ab))/2a  就可以算出n是多少了。
因为ans很大,所以要用大数。java大数也没有现成的开根号函数,所以要用二分来求 根。


import java.math.*;
import java.util.*;
import java.io.*;
 
public class Main{ 
	
	static BigInteger li=BigInteger.ZERO;
    static BigInteger yi=BigInteger.ONE;
    static BigInteger er=BigInteger.valueOf(2);
	public static BigInteger sqrtt(BigInteger n)
	{
		BigInteger l=yi,r=n,mid;
		while(l.compareTo(r)<=0)
		{
			mid=l.add(r).divide(er);
			
			if(mid.multiply(mid).compareTo(n)<0)
				l=mid.add(yi);
			else
				r=mid.subtract(yi);
			//System.out.println(l+" "+r);
		}
		return l;
	}
	
        public static void main(String[] args)
       {
                 Scanner input = new Scanner(System.in);

                 BigInteger a;
                  
                 while(input.hasNext())
                 {
                	 a=input.nextBigInteger(); 
                	 a=a.multiply(BigInteger.valueOf(8)); 
                	 a=a.add(BigInteger.ONE); 
                	 a=sqrtt(a); 
                	 System.out.println(a.subtract(BigInteger.ONE).divide(BigInteger.valueOf(2))); 
                 } 
       } 
}





URAL 1153. Supercomputer 二分求根

原文:http://blog.csdn.net/u013532224/article/details/44571661

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!