Blue Bridge Cup test questions basic exercises decomposition prime factor BASIC-16 JAVA

Foreword

I have been conducting interviews recently. Many of the written code is too lazy to post to the blog. It is now filled in, but there may be fewer comments. If you have any questions, please contact me

Exam questions basic exercises to decompose prime factors

Resource limit
Time limit: 1.0s Memory limit: 512.0MB

Problem description
  Find the prime factorization of all integers in the interval [a, b].

Input format
  Input two integers a, b.

Output format
  Each line outputs a number of decompositions, the form is k = a1 a2 a3 ... (a1 <= a2 <= a3 ..., k is also from small to large) (see the example for details)

Sample input
3 10

Sample output
3 = 3
4 = 2 2
5 = 5
6 = 2
3
7 = 7
8 = 2 2 2
9 = 3 3
10 = 2
5

Tip
  first sieve out all prime numbers, and then decompose.

Data scale and convention
  2 <= a <= b <= 10000

Code for this question

import java.util.Scanner;

public class PrimeDecomposition {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int[] array = new int[b - a + 1];
        if (a == b)
            array[0] = a;
        else
            for (int i = a, j = 0; i <= b; i++, j++)
                array[j] = i;
        for (int value : array) {
            StringBuffer st = new StringBuffer(value + "=");
            int z = 2;
            while (z <= value) {
                if (value % z == 0) {
                    if (st.charAt(st.length() - 1) != '=') st.append("*");
                    st.append(z);
                    value = value / z;
                    z = 2;
                } else
                    z++;
            }
            System.out.println(st);
        }
    }
}
Published 113 original articles · Liked 105 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/weixin_43124279/article/details/105419064