1153. Supercomputer
Time limit: 2.0 second
Memory limit: 64 MB
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
Problem Source: Ural Collegiate Programming Contest, April 2001, Perm, English Round
Tags: none
)
题意
给你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)));
}
}
}