问题是找到两个数字之间的平方数.
下面的代码可以处理小数字,但是数字很大.我怎么能纠正这个?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class NumOfSqrs {
public static void main(String[] args) {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
int line = 0;
int testCases;
int numOfSqrt = 0;
int j = 0;
while((input=br.readLine())!=null){
if(line == 0){
testCases = Integer.parseInt(input);
line = line +1;
}
else{
String[] splitter = input.toString().split(" ");
//Here splitter gives two numbers, we need to find no of sqrs b/w these numbers for eg say 3 and 9
for(int i = Integer.parseInt(splitter[0]); i<=Integer.parseInt(splitter[1]) ; i++){
String value = ""+Math.sqrt(i);
String[] isSqrt = value.toString().split("\\.");
//System.out.println(""+isSqrt[0] + "" + isSqrt[1]);
//Here lets say if 'i' is 4 (i.e 2.0) then isSqrt[0] = 2, isSqrt[1] = 0 and if isSqrt[1] != 1 then its obvious that its not a perfect square
if(isSqrt[1].length() == 1){
numOfSqrt++;
}
}
System.out.println(""+numOfSqrt);
}
numOfSqrt = 0;
}
}catch(IOException io){
io.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Boh*_*ian 14
您确定方块的技术(转换为字符串并在点上拆分)是狡猾的.
这也是不必要的 - 你可以在一行中使用纯粹的数字方法:
int low, high; // fill from input
int numOfSqrt = (int) (Math.floor(Math.sqrt(high)) - Math.ceil(Math.sqrt(low)) + 1);
Run Code Online (Sandbox Code Playgroud)