Pregunta

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();
    }

}
¿Fue útil?

Solución

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());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top