Как я могу сделать этот код быстрее? Spoj сказал, что предел времени превышен, когда я вставляю это решение.TLE в быстром умножении в spoj
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("the number of multiplications <= 1000: ");
int n = scanner.nextInt();
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply");
BigInteger l1 = new BigInteger(scanner.next());
System.out.print("Second number to multiply");
BigInteger l2 = new BigInteger(scanner.next());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
} else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
}
}
обновление: теперь я использовал буферизованный считыватель, но теперь я получаю неправильный ответ, хотя мои выходы правильные. Вот мой обновленный код
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("the number of multiplications <= 1000: ");
int n = Integer.parseInt(reader.readLine());
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply: ");
BigInteger l1 = new BigInteger(reader.readLine());
System.out.print("Second number to multiply: ");
BigInteger l2 = new BigInteger(reader.readLine());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
} else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
} catch (NumberFormatException e) {
System.err.println("invalid");
}
}
}
Заранее спасибо.
Скорость всегда будет опираться на то, как быстро кто-то вводит в System.in, независимо от того, сколько циклов вы вытесняете из утверждений. – Gimby
Пожалуйста, отформатируйте свой код, чтобы сделать его более читаемым. – Henry