简体   繁体   English

如何显示输入数字的 2 位数总和(质数)

[英]How possible to display the 2 digit sum of the inputted number (prime numbers)

It will only accept a non-negative even number (higher than 2) and extract the 2 prime numbers.它只会接受一个非负偶数(大于 2)并提取 2 个素数。 Here is the sample output:这是示例输出:

Enter the number: 20输入数字:20

The twin prime numbers of 20 are: 17 and 3 / 13 and 7 20 的孪生素数是:17 和 3 / 13 和 7

(17 + 3 = 20 and 13 + 7 = 20 also) But 17,3,13, and 7 is a prime number. (17 + 3 = 20 和 13 + 7 = 20 也是)但是 17、3、13 和 7 是质数。 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:但这是我的输出,我的输出只是打印 3-20 之间的所有孪生素数(即输入的数字)运行:

Enter the number: 20输入数字:20

The twin prime numbers of 20 are: 3 / 5 5 / 7 11 / 13 17 / 19 20 的孪生素数是: 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");
                }
            }
        }
    }
}

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM