day36 449 Prime factor decomposition (number theory, enumeration)

449. Prime factor decomposition

Knowing that the positive integer n is the product of two different prime numbers, try to find the larger prime number.

Input format The
input is only one line and contains a positive integer n.

Output format The
output is only one line, containing a positive integer p, which is the larger prime number.

Data range
6 ≤ n ≤ 2 ∗ 1 0 9 6≤n≤2∗10^96n2109
Input sample:

21

Sample output:

7

Ideas:

  1. We need to first understand a basic theorem of arithmetic as shown in the figure:
    Insert picture description here
    这说明合数一定可以分解成唯一的一组质数的乘积

  2. Questions already said given nis the product of two primes, it shows that nit must be a composite number, the other is nthe decomposition of the form is determined, it must be a prime number ×prime number (can not be a composite number ×composite number or a composite number ×prime number, Because in this case, the composite number will be decomposed into prime numbers and nbecome the product of three prime numbers, which does not match the meaning of the question).

  3. All numbers are about occur in pairs: If da ndivisor, then nd \ frac {n} {d }dnIt is the ndivisor.

  4. We can only enumerate the smaller divisors and then calculate the larger divisors. Then the range that needs to be enumerated satisfies: d ≤ ndd ≤ \frac{n}{d}ddn, Then d ≤ nd≤\sqrt{n}dn . So only need to enumerate n \sqrt{n}n Times.

Time complexity
Since only small divisors are enumerated, only n \sqrt{n}n Times, so the total time complexity is O (n) O(\sqrt{n})O (n )

Java code

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int t = (int)Math.sqrt(n);
        for(int i = 2;i <= t;i++){
    
    
            if(n % i == 0){
    
    //第一次遇到n的因子时,这个因子就是较小的那个因子
                System.out.println(n / i);//输出较大的那个因子后,可以break直接退出for循环了
                break;
            }
        }
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/YouMing_Li/article/details/114023065