Project Euler – Problem 13 Solution (Java)
http://projecteuler.net/index.php?section=problems&id=13
This one was tricky until I Googled “java big integer” and found out about Java’s BigInteger, lol. It made the problem much simpler. After I got the answer I saw some posts on the forum saying that only the sum of the first 11-15 (it varied) digits were needed, but I’m not fully convinced of that yet. The other digits could lead to values being “carried over”, which will impact the total sum. So, I still stand by my solution… for now
) I’ll keep thinking about the other solution and see if I’m able to convince myself one way or the other.
/* Project Euler - Problem 13 (http://projecteuler.net/index.php?section=problems&id=13)
*
* Saved the numbers to a file for neatness. Then just read from the file and used
* Java's BigInteger.
*/
public static void p13(){
String line = null;
BigInteger sum = BigInteger.ZERO;
try{
BufferedReader input = new BufferedReader (new FileReader("numbers.txt"));
while((line = input.readLine()) != null)
sum = sum.add(new BigInteger(line));
}
catch(IOException e){e.printStackTrace();}
System.out.println(sum.toString().substring(0,10));
}
Tina on February 1st 2009 in Project Euler