// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class FJ17 extends RecursiveTask<Integer> {
    private int val;
    private int start;
    private int end;
    public FJ17(int val, int start, int end) {
        this.val = val;
        this.start = start;
        this.end = end;
    }
    public int countMultipla() {
        int res = 0;
        for(int i = start; i <= end; i++) {
            if(i % val == 0) {
                res++;
            }
        }
        return res;
    }
    @Override
    public Integer compute() {
        int n = end - start + 1;
        if(n < 10_000_000) {
            return countMultipla();
        } else {
            FJ17 low = new FJ17(val, start, start + n/2);
            FJ17 high = new FJ17(val, start+n/2+1, end);
            // do not use:
            //invokeAll(low, high);
            //return low.join() + high.join();
            // use:
            high.fork();
            return low.compute() + high.join();
        }
    }
    public static void main(String[] args) {
        ForkJoinPool fjp = new ForkJoinPool(8);
        long t1 = System.currentTimeMillis();
        FJ17 o = new FJ17(4, 1, 1_000_000_000);
        fjp.invoke(o);
        int n = o.join();
        long t2 = System.currentTimeMillis();
        System.out.println(n + " in " + (t2 - t1));
    }
}
