题目1:从1加到10亿,有什么求解姿势?
姿势一:硬累加【大数据量慎用的求解方法】:
public static void test01() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long sum = 0L;
for (long i = 0L; i <= 10_0000_0000L; i++) {
sum += i;
}
System.out.println("test01: " + sum);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
}
姿势二:JDK 8的Stream 流求和,速度很快,姿势最佳【推荐】
import java.util.stream.LongStream
public static void test02() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().sum();
System.out.println("test02: " + sum);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
}
姿势三:ForkJoin求解法
class ForkJoinTest extends RecursiveTask<Long> {
private Long start;
private Long end;
private Long temp = 100000L;
ForkJoinTest(Long start, Long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if ((end - start) < temp) {
Long sum = 0L;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
} else {
long mid = (end + start) / 2;
ForkJoinTest task1 = new ForkJoinTest(start, mid);
task1.fork();
ForkJoinTest task2 = new ForkJoinTest(mid + 1, end);
task2.fork();
return task1.join() + task2.join();
}
}
}
public static void test03() throws ExecutionException, InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTest task = new ForkJoinTest(0L, 10_0000_0000L);
ForkJoinTask<Long> res = forkJoinPool.submit(task);
Long sum = res.get();
System.out.println("test03: " + sum);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
}