示例输入: 10 100
示例输出: 11,31,41,61,71,101
从上面的代码中我可以获得最大为71的样本输出值,如何获得b后面以1结尾的最接近的素数。
这是我尝试过的代码:
import java.util.*;
public class Program{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int i,j,count;
for(i=a;i<=b;i++)
{
for(j=2;j<=b;j++)
{
if(i%j==0)
break;
}
if(j==i && j%10==1)
{
System.out.println(i);
}
}
}
最佳答案
您不需要将一个数字除以它之前的数字来检查它是否是素数。您只需检查其平方根即可。检查https://en.wikipedia.org/wiki/Primality_test 。执行如下操作:
使用for
循环
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter two integers separated by space: ");
int a = in.nextInt();
int b = in.nextInt();
int i, j, sqrt;
// Note that there are three sections in the declaration of a 'for' loop:
// for(initialization;condition;change) where none of the sections is
// mandatory. There is no condition put in the loop syntax given below. The
// condition for termination has been put after printing the prime number.
for (i = a;; i++) {
sqrt = (int) Math.sqrt(i);
for (j = 2; j <= sqrt; j++) {
if (i % j == 0) {
break;
}
}
// If the loop with j completed without a break, the number is prime. Note that
// 1 is not a prime number.Also, the last digit of the number should be 1.
if (j > sqrt && Math.abs(i) != 1 && i % 10 == 1) {
System.out.print(i + " "); // Print the prime
if (i >= b) {// Condition for termination
break;
}
}
}
}
}
或者,使用 while
循环
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter two integers separated by space: ");
int a = in.nextInt();
int b = in.nextInt();
int i = a, j, sqrt;
while (true) {
sqrt = (int) Math.sqrt(i);
for (j = 2; j <= sqrt; j++) {
if (i % j == 0) {
break;
}
}
// If the loop with j completed without a break, the number is prime. Note that
// 1 is not a prime number.Also, the last digit of the number should be 1.
if (j > sqrt && Math.abs(i) != 1 && i % 10 == 1) {
System.out.print(i + " "); // Print the prime
if (i >= b) {// Condition for termination
break;
}
}
i++;
}
}
}
示例运行:
Enter two integers separated by space: 10 100
11 31 41 61 71 101
另一个示例运行:
Enter two integers separated by space: 10 200
11 31 41 61 71 101 131 151 181 191 211
关于java - 如何打印给定范围内以1结尾的素数以及b之后最接近的素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61030637/