...键盘输入两个整数,并输出这两个整数间的所有素数
发布网友
发布时间:2024-05-31 01:09
我来回答
共2个回答
热心网友
时间:2024-06-01 14:46
package com.test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sole = new Scanner(System.in);
int n1=0;
int n2 =0;
System.out.println("请输入第1个整数.");
n1 = sole.nextInt();
System.out.println("请输入第2个整数.");
n2 = sole.nextInt();
if(n1>n2){
n1=n1^n2;
n2=n1^n2;
n1=n1^n2;
}
for(int i = n1; i<=n2; i++){
if(f(i)!=0){
System.out.println(i);
}
}
}
public final static int f(int n){
if(n<1){
return 0;
}
int temp = (int)Math.sqrt(n);
int i=2;
for(; i<=temp;i++){
if(n%i==0){
break;
}
}
if(i-1==temp){
return n;
}
return 0;
}
}
热心网友
时间:2024-06-01 14:47
启动的时候以Java Applet的形式启动。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class GetPrimeNumber extends Applet implements ActionListener {
private static final long serialVersionUID = 1L;
TextField t1 = new TextField(5);
TextField t2 = new TextField(5);
Button b1 = new Button("求素数");
int m, n;
public void init() {
add(t1);
add(t2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
m = Integer.parseInt(t1.getText());
n = Integer.parseInt(t2.getText());
repaint();
}
public void paint(Graphics g) {
boolean f;
int i, j, k = 0;
for (i = m; i <= n; i++) {
f = true;
for (j = 2; j <= 2; j++)
if (i % j == 0) {
f = false;
break;
}
if (f) {
g.drawString(" " + i, (k % 10) * 20 + 20, (k / 10) * 30 + 80); // 输出素数
k = k + 1;
}
}
}
}