Project Euler

A Taste of Number Theory

Problem 48: Self Powers

The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.

The Catch

How to store and quickly calculate extremely large numbers.

The Light

Use Java's BigInteger class.

The Code

import java.math.BigInteger;

public class Problem48
{
  public static void main(String[] args)
  {
    BigInteger result = BigInteger.ZERO;
    BigInteger i = BigInteger.ONE;
    BigInteger index = BigInteger.ONE;
    BigInteger one = BigInteger.ONE;
    BigInteger limit = new BigInteger("1001");
    int exp = 1;

    for(; index.compareTo(limit) == -1; index = index.add(one))
    {
      BigInteger tmp = i.pow(exp++);
      result = result.add(tmp);
      i = i.add(one);
    }
    String s = result.toString();
    s = s.substring(s.length() - 10, s.length());
    System.out.println("Last 10 digits are " + s);
 }
}