从1加到10亿,如何优雅的快速求和

题目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());

    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

walking_w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值