"Blue Bridge Cup" Perfect Square Number (Java)

Question H

image-20220331154847461image-20220331154920485image-20220331154931726

Violent enumeration, TLE, after 7 examples, you can probably get a score of 50%~70%.

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        for (long i = 1; i <= n; i++) {
    
    
            // 将这个数开根号之后转为整形 砍掉后面的小数位 判断是否等于这个数字
            if ((long) Math.sqrt(i * n) * (long) Math.sqrt(i * n) == i * n) {
    
    
                System.out.println(i);
                return;
            }
        }
    }
}

Correct solution : In fact, the test point of this question is to decompose the prime factors, n ⋅ x = m 2 n x=m^2nx=m2 n n What is the minimum multiplication of n , which can makennThe number of prime factors in n becomes even; n
= P 1 α 1 × P 2 α 2 × . . . × P n α nn=P_1^{α1}×P_2^{α2}×...×P_n^{ αn}n=P1α 1×P2α 2×...×Pna _, if the degree of a prime factor α i α_iaiis an odd number, then we multiply by at least this prime factor, so this problem is to put nnDecompose the prime factors of n , look at the degrees of all its terms, multiply all the prime factors with odd degrees, and that's the answer.

时间复杂度 O( N ) O(\sqrt N)O(N )

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long res = 1;
        for (long i = 2; i * i <= n; i++) {
    
    
            if (n % i == 0) {
    
    
                int s = 0;
                while (n % i == 0) {
    
     // 分解质因子求次数
                    s++; 
                    n /= i;
                }
                if (s % 2 == 1) res *= i; // 如果是奇数 则乘起来
            }
        }
        if (n > 1) res *= n; // 表示还有一个质因子 次数是1
        
        System.out.print(res);
    }
}

For n > 1 n > 1n>1 For example,24 = 2 3 × 3 24 = 2^3×324=23×3 , at this time ourres = 2 res=2res=2 , but there is also a factor of3 33 is not counted, because we arewhile(n % i == 0)in the last step of the coden /= i = 3, the last factor is left unconsidered, and the number is 1, so finally multiply bynnn is enough,res = 2 × 3 = 6 res = 2 × 3=6res=2×3=6

Guess you like

Origin blog.csdn.net/weixin_53407527/article/details/123894773