编写一个判断素数的java程序?

2024-11-15 12:53:03
推荐回答(3个)
回答1:

import java.io.*;
class prime{
private int num;
static boolean isprime(int num){
if(num<=1) return false;
int i;
for(i=2;i<=num/2;i++)
if(num%i==0) return false;
return true;
}
}
class Main {

public static void main (String[] args)
throws IOException{
int num=0;
String data;
BufferedReader br = new
BufferedReader(new
InputStreamReader(System.in));
System.out.print( "请输入一个整数:" );
data=br.readLine ();
try{
num = Integer.parseInt (data);
}
catch(NumberFormatException e){}

if(prime.isprime (num)){
System.out.println ( num+"是素数!" );
}
else
System.out.println ( num+"不是素数!" );
}

}

祝君好运啊

回答2:

int a = 2;
if(2%2==1)
{
response.write("这是个质数");
}else
{
...
}
就是写判断是否为质数得公式

回答3:

public static void main(String[] args) {
int i = 0;
int j = 0;
for (i = 1; i <= 100; i++) {
for (j = 2; j <= i - 1; j++)
if (i % j == 0)
break;
if (j >= i)
System.out.println(i);
}
}