JAVA BigInteger class use Case 1: To find the integer portion of the square root of a large integer (SGU) __java

Source: Internet
Author: User
Tags square root time limit stringbuffer

Very Simple problem

Time limit:0.25 sec, Memory limit:1 MB

You are given natural number X. Find such maximum integer number that it square
is not greater than X.

Input

Input file contains number X (1≤x≤10^1000).

Output

Write answer in output file.

Sample Input

16

Sample Output

4

It is simple to ask for an integral part of the square root of a positive integer X that may be up to 1000 digits.

Beginners Java, Java BigInteger class to achieve Newton's iterative square root (many library functions do not know, on their own to write slightly).

Import Java.math. * ;
Import java.io. * ;

public class Solution ... {
Convert a string to a positive integer
static int str2int (String str)//0 <= the integer <= 2 ^ 31-1
... {
int ret = 0;
for (int i = 0, j = str.length (); i < J; i + +)
... {
RET = RET * + str.charat (i)-' 0 ';
}
return ret;
}
Convert a positive integer to a string
static String int2str (int i)//0 <= i <= 2 ^ 31-1
... {
StringBuffer sb = new StringBuffer ("0000000000");
int digit = 0;
if (i = = 0)
... {
return "0";
}
while (i > 0)
... {
Digit + +;
int low = i% 10;
I/= 10;
Sb.setcharat (10-digit, (char) (Sb.charat (10-digit) + low);
}
Return sb.substring (10-digit);
}
The integer portion of the square root of the positive integer (this is copied from the Hacker ' s Delight book)
static int isqrt (int x)//0 <= x <= 2 ^ 31-1
... {
int B, m = 0x40000000, y = 0;
while (M!= 0)
... {
b = y | M
Y >>= 1;
if (x >=b)
... {
x = b;
Y |= m;
}
M >>= 2;
}
return y;
}

public static void Main (string[] args) throws IOException
... {
BufferedReader br = new BufferedReader (
New InputStreamReader (system.in)
);
String str = br.readline ();
BigInteger Bi []
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.