顯示具有 數學運算 標籤的文章。 顯示所有文章
顯示具有 數學運算 標籤的文章。 顯示所有文章

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);

Java 練習(6):某個數值內哪些是質數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
        String str=JOptionPane.showInputDialog("請輸入1個整數");
        int a=Integer.parseInt(str);
        String s="";
        for (int i = 1; i <= a; i++) {
            boolean b = true;
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    b = false;
                }
            }
            if (b) {
                s=s+i+",";
            }
            
        }JOptionPane.showMessageDialog(null, s);

2015年7月17日 星期五

Java 練習(5):判斷是否為質數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
        String str = JOptionPane.showInputDialog("請輸入一個整數");
        int num = Integer.parseInt(str);
        boolean b = false;
        for (int i = 2; i < num; i++) { 
            if (num % i == 0) {//質數只能被1和自己整除,所以若小於num的每個數字都不能整除,則NUM為質數
                b = true;
                break;
            }
        }
        String s;
        if(b){
            s=num+"不是質數";
           
        }else{
            s=num+"是質數";
        }
        JOptionPane.showMessageDialog(null, s);