简体   繁体   中英

How to optimize code using Java concurrency [on hold]

This code is taking too much time to solve a Hackerrank problem. I want to use concurrency to solve it faster.

Hackerrank problem: Given a number N, find the number of ways to represent this number as a sum of 2 or more consecutive natural numbers.

public class WaysToSumNumber {

    static int countConsecutive(int num) {
        int count = 0;
        for (int i = 1; i * (i + 1) < 2 * num; i++) {
            float a = (float) ((1.0 * num - (i * (i + 1)) / 2) / (i + 1));
            if (a - (int) a == 0.0)
                count++;
        }
        return count;
    }

    public static void main(String[] args) {
        int num = 15;
        System.out.println(countConsecutive(num));
    }
}

It took me a minute to figure out how you were calculating, including that may help getting responses sooner. Seems like there is a solution from Arithmetic Progressions that you are using, where when you get an integer result from that a equation that should be a solution to problem. Once I found that out I was able to make it parallel and here is the solution.

    static int countConsecutive(int num) {
    return (int) IntStream.range(1, (int) Math.sqrt(2 * num)).parallel().filter(i -> {
        float a = (float) ((1.0 * num - (i * (i + 1)) / 2) / (i + 1));
        return a - (int) a == 0.0;
    }).count();
}

I have found though for some Java problems on the site it just runs too slow to finish. Some people have used better solutions for getting the input from scanner and other things. You can sometimes see this in the discussion thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM