2016-02-27 80 views
0

我想弄清楚一種方式,以更快和更優化的方式解決這個特定的問題。我不知道是否有可能讓這些代碼在多個內核和線程上運行,或者如何以某種方式將其卸載到GPU,但速度越快,計算得越好。是否有更優化的方式在java中進行簡單的計算?

public class numberCounter 
{ 
    public static void main(String[] args) 
    { 
     //Used only to check speed of calculation 
     long start = System.currentTimeMillis(); 

     //Initialized variables 
     double x, y, z; 

     //30 can be substituted out but i used it as a test. 
     //I am unable to calculate 31 and above. 
     long t = (long) Math.pow(2, 30); 

     //used later for counting 
     long counter = 0; 

     //starting number 
     System.out.println("Number - " + t); 

     for(int i = 1; i < t; i++) 
     { 
      x = i % 2; 
      y = i % 3; 
      z = i % 5; 

      if(x*y*z > 0) 
       counter++; 
     } 

     System.out.println(); 

     //prints out number of numbers that follow the rule above 
     System.out.printf("Numbers: %.0f\n", counter); 

     long end = System.currentTimeMillis(); 

     //prints out time taken 
     System.out.println((end - start) + " ms"); 

    } 
} 
+1

這看起來很像一個家庭作業問題,所以我會提供一些提示。提示#1:你應該能夠在一段時間內做到這一點。提示#2:當t = 30時櫃檯的價值是多少?當t = 60時? – user3486184

+0

這在技術上是我給自己的一個家庭作業問題,試圖證明一個數學問題,而我只用時間來看看需要多長時間來查看優化是否會使其更快。噸在30 = 286331153.我無法計算以上。 –

回答

1

最大的負擔是循環,所以最好加以解決,如果我們想獲得的東西進行優化。 你必須扭轉這個問題,而不是尋找2或3或5不可分割的數字,我們正在尋找可以被2或3或5整除的數字。由此產生的數字減去所有的數字會給我們數字不可分的數字乘以2或3或5.以這種方式,我們獲得具有恆定執行時間的算法。執行時間不依賴於輸入。

public static long indivisbleBy_2or3or5(long t) { 
    long x, y, z; 

    //amount of numbers divisible by 2, and several for 3 and 5. 
    x = t/2; 

    //amount of numbers divisible by 3 - numbers divisible by 3 and 2 = amount of numbers divisible by 3, and several for 5. 
    y = t/3; 
    y = y - y/2; 

    //amount of numbers divisible by 5 - numbers divisible by 5 and 2 - (numbers divisible by 5 and 3 - numbers divisible by 5 and 3 and 2) = number only divisible by 5 
    z = t/5; 
    z = z - z/2 - (z/3 - z/(2 * 3)); 

    //All numbers - (The amount of numbers divisible by 2, and several for 3 and 5 
    //+ The amount of numbers divisible by 3 and several for 5 + number only divisible by 5) 
    //= indivisible by 2 or 3 or 5 
    return t - (x + y + z); 
} 

我不知道是否「POW」有一些優化,但總體上更好地執行動作(2^15)^ 2,它提供了比2^30,這給29個操作15個操作。根據「分而治之」的原則。 :)

+0

2^x相當於1 << x。它始終是一個單一的ROL操作 –

+0

當然,但它會是X班。 –

+0

至少在x86 SHL SRC中,DST將在單個操作中將DST寄存器SRC時間移位,還是在DST時間內將SRC移入? –

相關問題