0
import java.util.Scanner;

class main{
public static void main(String args[]){
    Scanner input = new Scanner(System.in);
    int n,k,m=0;
    n = input.nextInt();
    k = input.nextInt();
    for(int c = 0 ; c < n ; c++){
        if(input.nextInt() % k == 0) m++;
    }
    System.out.println(m);
}
}

This is my solution to SPOJ Problem 442. I wanted to know how can i make this code run faster? What are techniques that can be used to make a java code faster?

Rushil Sablania
  • 526
  • 4
  • 15
  • 4
    SO is for programming Q&A. For codereview, you'd better ask at [Codereview](http://codereview.stackexchange.com/) – Alexis Pigeon Jan 07 '13 at 11:52
  • 7
    The only way to make that program faster is by typing quicker. This program does nothing besides waiting for user input in more than 99.99% of it's runtime. – jlordo Jan 07 '13 at 11:53
  • what are you trying to do in the program? – Shiva Komuravelly Jan 07 '13 at 11:53
  • 1
    (was confused too - the question becomes clearer after visiting the linked page) – Andreas Dolk Jan 07 '13 at 11:56
  • 2
    @jlordo I suspect it's only 99% of the time. ;) – Peter Lawrey Jan 07 '13 at 12:05
  • @TonyDay The problem clearly has nothing to do with branch prediction. But even if there were no I/O involved, how would that apply here (i.e. how do you remove the branch)? – assylias Jan 07 '13 at 12:10
  • @jlordo - only if input is from hand. The answer is doing more efficient then `Scanner`, specialized input buffering. – zch Jan 07 '13 at 12:16
  • 1
    @zch, I haven't looked at the link, but the program posted uses a `Scanner` reading from the console. So, input is _from hand_. If he wants a better answer, he needs to post a better question ;) – jlordo Jan 07 '13 at 12:20
  • @jlordo - no, it uses standard input. It is not necessarily console and surely not in this case. – zch Jan 07 '13 at 12:26
  • @assylias Very fair point. Apologies. – Tony Day Jan 07 '13 at 13:49

1 Answers1

4

My solution!

Scanner is too slow for huge input data.

You should write a simple Scanner by yourself then you'll get ac!

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {

  static int nextInt(InputStream in) throws IOException {
    int ch;
    for (; (ch = in.read()) < '0' || ch > '9';);
    int c = ch - '0';
    for (; (ch = in.read()) <= '9' && ch >= '0'; c = c * 10 + ch - '0');
    return c;
  }

  public static void main(String[] args) throws IOException {

    InputStream in = new BufferedInputStream(System.in, 4096);
    int n = nextInt(in);
    int k = nextInt(in);
    int t = 0;
    for (int i = 0; i < n; i++) {
      if (nextInt(in) % k == 0) t++;
    }
    System.out.println(t);
  }
}
jackalope
  • 1,554
  • 3
  • 17
  • 37