zoukankan      html  css  js  c++  java
  • Java实现 蓝桥杯 算法提高 因式分解

    算法提高 8-1因式分解
    时间限制:10.0s 内存限制:256.0MB
    提交此题
    问题描述
      设计算法,用户输入合数,程序输出若个素数的乘积。例如,输入6,输出23。输入20,输出22*5。
    样例
      与上面的样例输入对应的输出。
      例:

    120=22235
    数据规模和约定
      输入数据中每一个数在int表示范围内。

    import java.util.ArrayList;
    import java.util.Scanner;
    
    
    public class 因式分解 {
    	//获取2~A之间的所有质数
        public static ArrayList<Integer> getPrimes(int A) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            list.add(2);
            for(int i = 3;i <= A;i++) {
                if(judgePrime(i))
                    list.add(i);
            }
            return list;
        }
        //判断数A是否为质数,A为默认大于等于3的数
        public static boolean judgePrime(int A) {
            for(int j = 2;j <= A;j++) {
                if(A % j == 0) {
                    return false;
                }
                if(j > A / 2)
                    break;
            }
            return true;
        }
        
        public static void printResult(int A) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            ArrayList<Integer> tempList = getPrimes(A);
            int len = tempList.size();
            while(A > 1) {
                for(int i = 0;i < len;i++) {
                    if(A % tempList.get(i) == 0) {
                        list.add(tempList.get(i));
                        A = A / tempList.get(i);
                        break;
                    }
                }
            }
            //输出结果
            len = list.size();
            for(int i = 0;i < len - 1;i++) 
                System.out.print(list.get(i)+"*");
            System.out.print(list.get(len - 1));
            return;
            
        }
        
        public static void main(String[] args) {
           
            Scanner in = new Scanner(System.in);
            int A = in.nextInt();
    printResult(A);
        }
    
    }
    
    
  • 相关阅读:
    msp430时钟小结
    JDBC第一天连接池案例
    maltab几个常见的问题
    qt 获取天气的接口
    Qt Style Sheets制作UI特效
    qt 在指定区域添加图片
    qt 设置背景图片
    linux下mysql数据库的学习
    qt文本编辑器
    C++小游戏:扑克牌21点
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12948678.html
Copyright © 2011-2022 走看看