1. 程式人生 > 其它 >程式設計師也分三六九等

程式設計師也分三六九等

技術標籤:javajava演算法

計算10億之內所有的數之和:

三等:

   static void test() {
        long starttime = System.currentTimeMillis();
        long sum = 0;
        for (Long i = 0L; i < 1000000000L; i++) {
            sum += i;
        }
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - starttime)
;// test();//4807 }

六等:

public class ForkJoinTest extends RecursiveTask<Long> {


    private long start;
    private long end;
    private long temp = 10000L;
    private long sum;

    public ForkJoinTest(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
protected Long compute() { if ((end - start) < temp) { for (Long i = start; i < end; i++) { sum += i; } return sum; } else { Long middle = (end + start) / 2; ForkJoinTest forkJoinTest = new ForkJoinTest
(start, middle); forkJoinTest.fork(); ForkJoinTest forkJoinTest2 = new ForkJoinTest(middle + 1, end); forkJoinTest2.fork(); return forkJoinTest.join() + forkJoinTest2.join(); } } }

    static void test2() throws ExecutionException, InterruptedException {
        long starttime = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinTest = new ForkJoinTest(0L, 1000000000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinTest);
        Long aLong = submit.get();
        long endtime = System.currentTimeMillis();

        System.out.println(endtime - starttime);// test2();//4138

    }

九等:

 static void test3() {
        long starttime = System.currentTimeMillis();
        LongStream.rangeClosed(0L, 1000000000L).parallel().reduce(0, Long::sum);
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - starttime);//test3()//271

    }