Quote
1 3
2 4
5 6
7 8
2 4
5 6
7 8
The program would then respond with the sum of 1257 + 3468. Since M can be at most 1 million digits, it makes sense to use a big integer. I did that and what I find is my program takes too long. It's not the addition that is taking too long, is the fact that I am looping 1 million times to build the nums.
Adding is fast and easy. I thought what I would do is instead of building strings is I would add the two digits and then a second iteration would deal with carries. However that is even worse because it would perform two 0(n) iterations. My first program required one 0(n) iteration but that still took way too long.
The problem is input takes way too long. The program has to run in 3 seconds but it takes 30 seconds to read the input. Does anybody know any faster way to read input?
Anyway my two attempts are:
import java.util.*;
import java.io.*;
class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
//Scanner fin =new Scanner(new FileReader("sums.txt"));
Scanner fin = new Scanner(System.in);
int[] nums;
int N;
int length; // length of each number
N = fin.nextInt();
while (N > 0) {
length = fin.nextInt();
nums = new int[length];
for (int i=0;i<length;i++) {
nums[i] = fin.nextInt() + fin.nextInt();
}
for (int i=length-1;i>0;i--) {
nums[i-1] += (nums[i]/10);
nums[i] %= 10;
System.out.print(nums[i]);
}
System.out.println();
N--;
if (N != 0) {
System.out.println();
}
}
fin.close();
}
}
Big Integer:
import java.util.*;
import java.io.*;
import java.math.BigInteger;
class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
//Scanner fin =new Scanner(new FileReader("sums.txt"));
Scanner fin = new Scanner(System.in);
int N;
int length; // length of each number
String sNum1 = "";
String sNum2 = "";
N = fin.nextInt();
while (N > 0) {
length = fin.nextInt();
sNum1 = "";
sNum2 = "";
for (int i=0;i<length;i++) {
sNum1 += fin.nextInt();
sNum2 += fin.nextInt();
}
System.out.println(new BigInteger(sNum1).add(new BigInteger(sNum2)));
N--;
if (N != 0) {
System.out.println();
}
}
fin.close();
}
}
I'm sure my algorithms are correct. They get the correct answer but they don't run quick enough. Thoughts? I thought to use buffered input. Would that make it fast enough? There is a lot that I do not know about input. I know enough to be functional but it is evident that the Scanner is not efficient for large inputs.
What about scanf or cin? It's a different language but is it possible that methods in Java just aren't fast enough?


Sign In
Create Account


Back to top











