Java Algorithm Descendants of Prime Numbers

Question description

In the last season, we mentioned the loneliness of prime numbers. In fact, from another perspective, their composite numbers are all descendants of prime numbers, because composite numbers can be obtained by multiplying and combining prime numbers.
  If a composite number is obtained by multiplying two prime numbers, then we call it a direct descendant of the prime numbers. Now, given a series of natural numbers, determine whether they are direct descendants of prime numbers.

Input
Input description:
  The first line is a positive integer T, indicating the number of natural numbers that need to be judged
  Next T lines, each line contains a natural number to be judged
Input example:
4
3< a i=7> 4 6 12


output

Output description:
  There are T lines in total. For the natural numbers given in the input, determine whether they are direct descendants of prime numbers. If so, output Yes, otherwise output No
Output sample:
No
Yes
Yes
No< /span>

HINT: Time limit: 1.0s Memory limit: 256.0MB
  1<=T<=20
  2<=Natural number to be judged< ;=105

Problem-solving ideas

After entering the number, just find the prime number less than or equal to the number and then divide the numbers, and finally determine whether the divisor is a prime number.

code

import java.util.Scanner;

public class Main {
    
    

    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        int[] data = new int[t];
        for (int i = 0; i < t; i++) {
    
           //输入数字
            data[i] = sc.nextInt();
        }
        for (int i = 0; i < t; i++) {
    
           //调用方法
            find(data[i]);
        }
    }
    private static void find(int i) {
    
    
        int j;
        for (j = 2; j < i; j++) {
    
    
            if (i % j == 0) {
    
    
                int m;
                for (m = 2; m < j && j % m != 0; m++);  //寻找i以内的质数
                if (m == j) {
    
    
                    int d = i / j;                     //相除
                    for (m = 2; m < d && d % m != 0; m++);
                    if (m == d) {
    
                           //判断除数是否也为质数
                        System.out.println("Yes");
                        break;
                    }
                }
            }
        }
        if (j == i) {
    
                                       //若不为则输入NO
            System.out.println("No");
        }
    }
}

おすすめ

転載: blog.csdn.net/joreng/article/details/123706102