2015年7月18日 星期六

Java 練習(7):利用continue敘述,找出小於45的最大質數

Java 7 教學手冊第五版 第五章習題

18.利用continue敘述,找出小於45的最大質數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
        String str = JOptionPane.showInputDialog("請輸入1個整數");
        int a = Integer.parseInt(str);
        int count=0;
        String s = "";
        for (int i = a; i >= 1; i--) {

            for (int j = 1; j * j <= i; j++) {
                if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0 || i % (6 * j + 1) == 0 || i % (6 * j + 5) == 0) {
                    continue;
                    //質數判斷,不可被2,3,5,6n+1,6n+5整除
                }
                count = count+1;
                if(count==1){
                    s=i+"";
                    break;
                }
            
            }

        }

        JOptionPane.showMessageDialog(null, s);

沒有留言:

張貼留言