Java程序设计:用“埃氏筛法”求2~n以内的素数

用“埃氏筛法”求2~100以内的素数。2~100以内的数,先去掉2的倍数,再去掉3的倍数,再去掉5的倍数,……依此类推,最后剩下的就是素数。

‏要求使用数组及增强的for语句。

写了个带图形界面的,源代码如下:

Main.java

package leet;


import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Gui.init();
    }

    public static String calc(int num) {
        boolean[] isPrime = new boolean[num];
        Arrays.fill(isPrime, true);
        //1不考虑,设为false
        isPrime[0] = false;
        //2是质数,从3开始。
        int count = 1;
        for (int i = 2; i < num; i++) {
            for (int j = 1; j < i; j++) {
                if (isPrime[j]) {
                    if ((i + 1) % (j + 1) == 0) {
                        isPrime[i] = false;
                        break;
                    }
                }
            }
            if (isPrime[i]) {
                count++;
            }
        }
        int[] res = new int[count];

        for (int i = 0, j = 0; j < count; i++) {
            if (isPrime[i]) {
                res[j] = i + 1;
                j++;
            }
        }
        String result = "素数共有" + count + "个,分别为:\n";
        for (int i : res) {
            result = result + i + ", ";
        }
        return result;
    }
}

Gui.java

package leet;

import javax.swing.*;

public class Gui {
    private JPanel panel1;
    private JButton button1;
    private JTextArea textArea1;
    private JTextField textField1;
    private JLabel label1;
    private JScrollPane jscroll;

    public Gui() {
        button1.addActionListener(e -> textArea1.setText(Main.calc(getIntTextField1())));
    }

    public static void init() {
        try {
            // 设置本机系统外观
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        JFrame frame = new JFrame("Gui");
        frame.setContentPane(new Gui().panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public int getIntTextField1() {
        int ret = 0;
        try {
            ret = Integer.parseInt(textField1.getText());
            if (ret < 3) {
                ret = 0;
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            textArea1.setText("请输入不小于2的整数!");
        }
        return ret;
    }
}

运行效果如图: