import java.math.*;
public class SumOfNumbers {
public static void main(String... args) {
for (int pow = 1; pow < 1_000_000_000; pow *= 10) {
long time = System.nanoTime();
try {
System.out.printf("pow = %,d%n", pow);
var sum = getSum(new BigInteger("10").pow(pow));
System.out.println(sum.bitLength());
} finally {
time = System.nanoTime() - time;
System.out.printf("time = %dms%n", (time / 1_000_000));
}
}
}
private static BigInteger getSum(BigInteger upto) {
return upto.multiply(upto.add(
BigInteger.ONE))
.shiftRight(1);
}
}
Can be improved with my parallelMultiply() method :-)
I would be more interested in how programmers respond to the challenge. For example, if you do use the algorithm for O(1), how do you avoid overflowing the integer for the same maximum size? And what is that maximum size of n? What about using a long? And what would the maximum size be then? And what about BigInteger? What would the complexity be then? How about calculating the sum to 1 billion? 1 trillion? With BigInteger, we no longer have O(1), but rather O(n^1.46) in Java 8 onwards. Before that it was O(n^2). And yes, this has little to do with programming, but I personally would expect any programmer to at least know that the sum of integers is n * (n 1) / 2. I figured that out by myself when I was 10.