Blue Bridge Cup basic exercises decomposition of the quality factor (JAVA)

Problem Description

Determined interval [a, b] for all integers prime factor decomposition.

Input format
  input two integers a, b.

Output format
  for each output line a number of decomposition, the form A1 = K A2 A3 ... (A1 <= A2 <A3 = ..., K is small to large) (see Specific examples)

Sample input
310

Sample Output
3 3 =
4 = 2 * 2
5 5 =
6 = 2 * 3
. 7 = 7
8 = 2 * 2 * 2
9 = 3 *
10 = 2 * 5

Problem-solving ideas

    In order to achieve a qualitative factor decomposition, we need to find all the number to be less than the decomposition of primes. Then starting from the smallest prime number selected sequentially, and can be spliced.

Algorithm is as follows

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int begin = input.nextInt();//起始数
        int end = input.nextInt();//终止数
        for (int i = begin; i <= end; i++) {
            int temp = i;//将要进行分解的数依次赋予中间变量temp
            System.out.print(temp + "=");
            for (int j = 2; j <= i; j++) {//依次查找从2到i之间的素数
                if(temp == 1) break;
                if(isPrime(j)){//找到素数进行因数分解操作
                    while(temp % j == 0){//当temp包含该素数时则将该素数打印
                        if(temp == j){
                            System.out.println(j);
                        }else{
                            System.out.print(j + "*");
                        }
                        temp = temp / j;//打印该素数后,则将该素数剔除出去,重新修改temp值进行操作,以保征,数值最小的素数优先考虑。
                    }
                }
            }
        }
    }
    //判断是否是素数的方法
    public static boolean isPrime(int n){
        if(n==2||n==3)  return true;
        if(n%6!=1&&n%6!=5)  return false;
        for(int i=5;i<=Math.floor(Math.sqrt(n));i+=6)
            if(n%i==0||n%(i+2)==0)  return false;
        return true;
    }
}

More blog Welcome to my personal blog

Guess you like

Origin www.cnblogs.com/alex-jzw/p/12422975.html