URAL 1153. Supercomputer 二分求根

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 < 10 600) 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 
Tags: none   (
hide tags for unsolved problems
)


题意

给你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))); 
                 } 
       } 
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值