英文:
How possible to display the 2 digit sum of the inputted number (prime numbers)
问题
import java.util.Scanner;
class Prime {
boolean prime(int a) {
int count = 0;
for (int x = 1; x <= a; x++) {
if (a % x == 0) {
count++;
}
}
switch (count) {
case 2:
return true;
default:
return false;
}
}
public static void main(String args[]) {
Prime twin = new Prime();
Scanner sc = new Scanner(System.in);
int higherThan2 = 3;
System.out.print("Enter the number: ");
int number = sc.nextInt();
if (higherThan2 >= number) {
System.out.println("Must be higher than 3!");
} else {
System.out.println("\nThe twin prime numbers of " + number + " are: ");
for (int i = higherThan2; i <= (number - 2); i++) {
if (twin.prime(i) == true && twin.prime(i + 2) == true) {
System.out.print(i + " / " + (i + 2) + "\n");
}
}
}
}
}
英文:
It will only accept a non-negative even number (higher than 2) and extract the 2 prime numbers. Here is the sample output:
Enter the number: 20
The twin prime numbers of 20 are: 17 and 3 / 13 and 7
(17 + 3 = 20 and 13 + 7 = 20 also) But 17,3,13, and 7 is a prime number. I don't know how to do it, please, thankyou!
But here is my output, my output is just to print all twin prime between 3-20 (that is inputted number)
run:
Enter the number: 20
The twin prime numbers of 20 are:
3 / 5
5 / 7
11 / 13
17 / 19
I don't know how to do the specific problem.
Here is my code btw:
import java.util.Scanner;
class Prime {
boolean prime(int a) {
int count = 0;
for (int x = 1; x <= a; x++) {
if (a % x == 0) {
count++;
}
}
switch (count) {
case 2:
return true;
default:
return false;
}
}
public static void main(String args[]) {
Prime twin = new Prime();
Scanner sc = new Scanner(System.in);
int higherThan2 = 3;
System.out.print("Enter the number: ");
int number = sc.nextInt();
if (higherThan2 >= number) {
System.out.println("Must be higher than 3!");
} else {
System.out.println("\nThe twin prime numbers of " + number + " are: ");
for (int i = higherThan2; i <= (number - 2); i++) {
if (twin.prime(i) == true && twin.prime(i + 2) == true) {
System.out.print(i + " / " + (i + 2) + "\n");
}
}
}
}
}
答案1
得分: 1
你可以试试这个。它可以工作,但我不认为这是最好的。
System.out.println("与" + number + "相邻的孪生质数是:");
for (int i = higherThan2; i < number; i++)
for (int j = number; j > higherThan2; j--)
if (twin.prime(i) && twin.prime(j) && i + j == number)
System.out.print(i + " / " + j + "\n");
英文:
You can try this. It works, but I don't think it's the best
System.out.println("\nThe twin prime numbers of " + number + " are: ");
for(int i = higherThan2; i < number; i++)
for(int j = number; j > higherThan2; j--)
if(twin.prime(i) && twin.prime(j) && i + j == number)
System.out.print(i + " / " + j + "\n");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论