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?

4

1 回答 1

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);
  }
}
于 2013-01-07T12:20:41.500 回答