2013-01-07 29 views
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); 
} 
} 

這是我對SPOJ Problem 442的解決方案。 我想知道如何讓這段代碼更快運行?什麼是可以用來更快地創建java代碼的技術?在java中減少程序運行時間 - 快速製作代碼

+4

SO是用於編程問答。對於codereview,你最好在[Codereview](http://codereview.stackexchange.com/)上詢問 –

+7

讓這個程序更快的唯一方法就是更快地輸入。除了等待超過99.99%的運行時間的用戶輸入之外,該程序不會做任何事情。 – jlordo

+0

你想在程序中做什麼? –

回答

4

我的解決方案!

Scanner對於龐大的輸入數據太慢。

你應該自己寫一個簡單的掃描儀,那麼你會得到交流!

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); 
    } 
} 
+0

設置緩衝區大小爲4096會變得更快 – jackalope

+0

非常感謝!有效! –

+1

您在nextInt函數中的第一個「for」的條件應該如下:for(;(ch = in.read())< '0' || ch >'9';); –