使用gui实现“筛选法”求2~n以内的所有素数过程
用“筛选法”求2~n以内的所有素数:先去掉2的倍数,再去掉3的倍数,再去掉4的倍数,…,依此类推,最后剩下的就是素数。试按GUI方式图示化求解过程。
package work12;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Work12 extends JFrame {
private JFrame jf;
private JPanel jp;
private JTextArea jta1, jta2;// 文本域
private JButton jb;
private JLabel jl1, jl2;
public int findi(int[] b, int m) {
return b[m];
}
public void print(int[] b) { // 输出数组中所有不为0的数
for (int i = 2; i < b.length; i++) {
if (b[i] != 0) {
jta2.append(String.valueOf(b[i]) + " ");
}
}
}
public Work12() {
jf = new JFrame("求解");
jf.setBounds(300, 300, 1000, 400);
jp = new JPanel();
jp.setLayout(null);
jl1 = new JLabel("输入:");
jl1.setBounds(20, 10, 40, 40);
jta1 = new JTextArea();
jta1.setBounds(60, 20, 70, 20);
jl2 = new JLabel("求解过程:");
jl2.setBounds(200, 10, 80, 40);
jta2 = new JTextArea();
JScrollPane jS = new JScrollPane(jta2);
jS.setBounds(280, 20, 650, 300);
jp.add(jS);
jb = new JButton("求解");
jb.setBounds(60, 100, 80, 50);
jp.add(jl1);
jp.add(jl2);
jp.add(jta1);
jp.add(jb);
jf.add(jp, BorderLayout.CENTER);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int n = Integer.parseInt(jta1.getText());
int[] a = new int[n+1];
int count = (int) Math.sqrt(n + 1);
//初始化数组
for (int i = 1; i < n + 1; i++) {
a[i] = i;
}
if (n == 1) {
jta2.append("无素数");
} else if (n == 2) {
jta2.append("除以" + 2 + "的结果:" + 2);
}
if (findi(a, m) != 0) {
for (int m = 2; m <= count; m++){
for (int k = 2; k < n + 1; k++) {
if (a[k] % findi(a, m) == 0 && a[k] != findi(a, m)) {
a[k] = 0;
}
}
jta2.append("除以" + m + "的结果:");
print(a);
jta2.append("\n");
}
}
}
});
}
public static void main(String[] args) {
new Work12();
}
}