java编程设计函数su_shu(n)判断n是否是素数,设计函数su_shu_2(n1)输出 n1这个7位数内的所有2至7位相邻数字是素数。 要求1: n通过随机函数生成;
时间: 2024-02-17 18:02:50 浏览: 59
好的,我理解了你的要求。以下是代码实现:
```java
import java.util.Random;
public class PrimeNumber {
// 判断一个数是否是素数
public static boolean su_shu(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
// 输出n1这个7位数内的所有2至7位相邻数字是素数
public static void su_shu_2(int n1) {
for (int i = 2; i <= 6; i++) {
int start = (int) Math.pow(10, i-1);
int end = (int) Math.pow(10, i) - 1;
for (int j = start; j <= end; j++) {
int num1 = j / (int) Math.pow(10, i-2);
int num2 = j % (int) Math.pow(10, i-2);
if (su_shu(num1) && su_shu(num2)) {
System.out.println(j);
}
}
}
}
public static void main(String[] args) {
// 生成一个随机数
Random random = new Random();
int n = random.nextInt(1000000);
if (su_shu(n)) {
System.out.println(n + "是素数");
} else {
System.out.println(n + "不是素数");
}
System.out.println("2至7位相邻数字是素数的数有:");
su_shu_2(1234567);
}
}
```
代码中,`su_shu`函数用于判断一个数是否是素数,`su_shu_2`函数用于输出一个7位数内的所有2至7位相邻数字是素数的数。
在`main`函数中,我们先生成一个随机数`n`,判断它是否是素数。然后调用`su_shu_2`函数,输出2至7位相邻数字是素数的数。
注意,我们这里为了方便,将`su_shu_2`函数的参数设置为了固定的`1234567`,你可以根据需要进行修改。
阅读全文
相关推荐















