1,首先明确什么是质数,只有1和本身两个约数叫做质数
2,从键盘读入我们的数据
3,写一个方法判断是不不是质数
4,输出结果
5,看代码
package com.sxt.jframe;
import java.util.Scanner;
public class ZhiShu {
public static void main(String[] args) {
System.out.println("请输入一个数");
int num = new Scanner(System.in).nextInt();
if (judgeNum(num)) {
System.out.println(num + "\t不是素数");
} else {
System.out.println(num + "\t是素数");
}
}
//判断是否是素数
private static boolean judgeNum(int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
return true;
}
return false;
}
}
6,运行效果如下
import java.io.*;
import java.util.Scanner;
public class Prime {
public static void main(String args[]) {
System.out.println("请输入一个数字:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int count = 0;
if (isPrimes(num)) {
System.out.println(num + "是一个质数!");
}
else {
System.out.println(num + "不是一个质数!");
}
System.out.println(num+"后的3个质数为:");
num = num+1;
loop:while(count<3)
{
//num = num+1;
if(isPrimes(num))
{
System.out.println(num);
count++;
num++;
continue loop;
}
else
{
num++;
continue loop;
}
}
}
public static boolean isPrimes(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}