#4385: JAVA 一值超時......


wangpiju (wangpiju)


想了很久 程式碼如下:

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {

        int number;


        Scanner input = new Scanner(System.in);
        boolean th = true;
        while (input.hasNext()) {
            number = input.nextInt();
            for (int i = 2; i < number ; i++) {
                if (number % i == 0) {
                    th = false;
                    break;
                } else {
                    th = true;
                }
            }
            if (th) {
                System.out.println("質數");
            } else {
                System.out.println("非質數");
            }

        }

 

    }
}

 

在netbean上沒問題

怎一放上來就一值超時了

有更好的演算法嗎?

謝謝各位,請幫幫我