Skip to content

Instantly share code, notes, and snippets.

@olegchir
Created November 17, 2016 21:37
Show Gist options
  • Save olegchir/91acba30cbdc0fb971b03d59a34eeff4 to your computer and use it in GitHub Desktop.
Save olegchir/91acba30cbdc0fb971b03d59a34eeff4 to your computer and use it in GitHub Desktop.
/**
* Created by olegchir on 18.11.2016.
*/
import java.math.BigInteger;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
class Sum extends RecursiveTask<BigInteger> {
private static final BigInteger MAX = new BigInteger("1000000000");
private static final BigInteger STREAK = MAX.divide(new BigInteger("16"));
private static final BigInteger TWO = new BigInteger("2");
BigInteger low;
BigInteger high;
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
BigInteger result = Sum.run();
long endTime = System.currentTimeMillis();
System.out.println(result.toString());
System.out.println("---");
System.out.println(endTime - startTime);
}
Sum(BigInteger lo, BigInteger hi) {
low = lo;
high = hi;
}
protected BigInteger compute() {
if(high.subtract(low).compareTo(STREAK) <= 0) {
BigInteger sum = BigInteger.ZERO;
BigInteger i = low;
while(true) {
i = i.add(BigInteger.ONE);
if (i.compareTo(high) > 0) {
break;
} else {
sum = sum.add(i);
}
}
return sum;
} else {
BigInteger mid = low.add(high.subtract(low).divide(TWO));
Sum left = new Sum(low, mid);
Sum right = new Sum(mid, high);
left.fork();
BigInteger rightAns = right.compute();
BigInteger leftAns = left.join();
return leftAns.add(rightAns);
}
}
static BigInteger run() {
return ForkJoinPool.commonPool().invoke(new Sum(BigInteger.ZERO, MAX));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment