0

I'm trying to solve this problem in Java but it gives me an error. The reason is that I can't achieve processing 2.5MB of input data per second at runtime. I want to know is there any way to speed up my code?

public class Main {

    final static int size = 5000;
    static int[] result = new int[size];

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int k = input.nextInt();
        int divided = 0;

        BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));

        try {
            while (n-- > 0) {

                result[n] = Integer.parseInt(bi.readLine());
                if (result[n] % k == 0)
                    divided++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(divided);

        input.close();
    }

}

1 Answer 1

1

What purpose does the result array serve? You are only ever indexing into it to store the number you just parsed, and then immediately again to check its divisibility. Get rid of the array, and make the loop just:

while(n-- > 0)
    if (Integer.parseInt(bi.readLine()) % k == 0)
        divided++;


You may wish to compare its performance without the BufferedReader, since the buffering might actually be what's slowing it down.
Personally, I would use the Java 8 Streams API to do this, because it is easy to make it a parallel operation. Something like this:

Scanner input = new Scanner(System.in);
final int n = input.nextInt(), k = input.nextInt();

InputStreamReader in = new InputStreamReader(System.in);

System.out.println(
        IntStream.generate(()->Integer.parseInt(in.readLine()))
                 .limit(n)
                 .parallel()
                 .filter(a->a%k==0)
                 .count());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.