1
這是一個Java程序,可從1-500000查找具有最大除數的數字。此線程程序每次向我顯示不同的答案
public class Medium2 {
static int count1 = 1;
static int count2 = 1;
static int big_count = 0;
static int big = 0;
主要方法
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
public void run() {
實現放在這裏
for (int num = 1; num <= 500000; num++) {
for (int i = 2; i <= num; i++) {
if (num % i == 0) { //Actual Logic
count1++;
}
}
if (count1 > big_count) {
big_count = count1; //Number of Divisors
big = num; //Largest Number
}
count1 = 1;
}
}
};
和線程執行
Thread thread1 = new Thread(runnable1); //Threads
Thread thread2 = new Thread(runnable1);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException ie) {
;
}
System.out.println("Biggest: " + big + "\nNumber of Divisors for " + big + " = " + big_count);
}
}
但它給不同的答案每次。實際答案是:498960和200除數
「實際的答案是:」......不,它不是。實際的答案取決於運行,而不取決於你的想法。你會得到不同的結果,因爲每次都有不同的結果 – Stultuske
「but」從哪裏來?你的程序在數據競賽中是膝下的。 –
線程在不同運行時會給出不同的結果 –