Search code examples
javaoptimizationiouser-inputinputstream

Which is the most efficient way of taking input in Java?


I am solving this question.

This is my code:

import java.io.IOException;
import java.util.Scanner;


public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] t = new int[n];
        int count = 0;
        for (int i = 0; i < n; i++) {
            t[i] = sc.nextInt();
            if (t[i] % k == 0) {
                count++;
            }
        }
        System.out.println(count);

    }
}

But when I submit it, it get's timed out. Please help me optimize this to as much as is possible.

Example

Input:

7 3
1
51
966369
7
9
999996
11

Output:

4

They say :

You are expected to be able to process at least 2.5MB of input data per second at runtime.

Modified CODE

Thank you all...I modified my code and it worked...here it is....

 public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        int n = Integer.parseInt(input[0]);
        int k = Integer.parseInt(input[1]);
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (Integer.parseInt(br.readLine()) % k == 0) {
                count++;
            }
        }
        System.out.println(count);
    }

regards

shahensha


Solution

  • This could be slightly faster, based on limc's solution, BufferedReader should be faster still though.

    import java.io.IOException;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int k = sc.nextInt();
            int count = 0;
            while (true) {
                try {
                    if (sc.nextInt() % k == 0) {
                        count++;
                    }
                } catch (NoSuchElementException e) {
                    break;
                }
            }
            System.out.println(count);
    
        }
    }