ライト:
サンプル入力:10 100
出力例:11,31,41,61,71,101
上記のコードから、私はBの後1で終わる最も近い素数を取得する方法、値71件までサンプルの出力値を得ることができます。
ここで私が試したコードは次のとおりです。
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);
}
}
}
アービンド・クマールのAvinash:
- あなたはそれが上限値に等しいかどうかをチェックできるように、最後の素数を格納する変数を持っている必要があります
- あなたはそれが素数であるかどうかを確認するために、それまでの数字で番号を分割する必要はありません。あなたはその平方根までチェックする必要があります。チェックhttps://en.wikipedia.org/wiki/Primality_testを
次のように実行します。
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, lastPrime = 0;
for (i = a; i <= b; 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
lastPrime = i;// Store the prime to lastPrime
}
}
// If the last prime is not equal to the upper limit, find the next prime
if (b != lastPrime) {
boolean nextPrimeFound = false;
do {
sqrt = (int) Math.sqrt(i);
for (j = 2; j <= sqrt; j++) {
if (i % j == 0) {
break;
}
}
if (j > sqrt && Math.abs(i) != 1 && i % 10 == 1) {
nextPrimeFound = true;
System.out.println(i);
}
i++;
} while (!nextPrimeFound);
}
}
}
サンプルを実行します。
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
次のようにプログラムをモジュールを作成するためには、関数に繰り返しコードを置くことができます。
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, lastPrime = 0;
for (i = a; i <= b; i++) {
if (isPrimeEndingWith1(i)) {
System.out.print(i + " "); // Print the prime
lastPrime = i;// Store the prime to lastPrime
}
}
// If the last prime is not equal to the upper limit, find the next prime
if (b != lastPrime) {
boolean nextPrimeFound = false;
do {
if (isPrimeEndingWith1(i)) {
nextPrimeFound = true;
System.out.println(i);
}
i++;
} while (!nextPrimeFound);
}
}
static boolean isPrimeEndingWith1(int n) {
if (Math.abs(n) == 1 || n == 0) {
return false;
}
int sqrt = (int) Math.sqrt(n), j;
for (j = 2; j <= sqrt; j++) {
if (n % 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(n) != 1 && n % 10 == 1) {
return true;
}
return false;
}
}