• 质因数分解


    题目:质因数分解

    题目说明:

    请设计一程式,输入一个正整数,改用质因数乘积表达此数,若该质因数出现多次,则用次方表示之。

    例如:

    n 12=2^2*3

    n 50=2*5^2

    Input:

    输入一正整数n

    Output:

    n的质因数分解,用空格隔开因数。

    Sample Input:

    240

    Sample Output:

    240=2^4*3*5


    答案:

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    
    public class zhishufenjie {
        
        private static Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        private static List<Integer> yinshu = new ArrayList<Integer>();
        
    
        public static void main(String[] args) {
        
            Scanner scan = new Scanner(System.in);
            int j =scan.nextInt();
          System.out.print(j+"=");
        
            fengjie(j);
            playResult(map,yinshu);
            
        }
        
         public static void fengjie(int n){
             int flag=1;
             while (n > 1) {
                    for (int i = 2; i <= n; i++) { 
                        if (n % i == 0) { 
                            flag=i;
    
                            if(!yinshu.contains(i)){
                                yinshu.add(i);
                            }
                            
                            if(!map.containsKey(i)){
                                map.put(i, 1);
                                
                            }else{
                                map.put(i, map.get(i)+1);
                            }
    
                            break;
                        }
                    }
                    n = n / flag; 
                }
             
    
                }
         
        public static void playResult(Map<Integer,Integer> map,List<Integer> yinshu){
           String result ="";
            for(int i=0;i<yinshu.size();i++){
                if(map.get(yinshu.get(i))!=1){
                    result+="*"+yinshu.get(i)+"^"+map.get(yinshu.get(i));
                }else{
                    result+="*"+yinshu.get(i);
                }
                
            }  
            
            System.out.println(result.substring(1));
     }
    
          
    }
  • 相关阅读:
    C# String 与 byte 互转
    ajax 传值 中文乱码问题
    Js 日期处理
    sqlCacheDependency 更新缓存Cache
    SQL分割字符串,返回临时表
    E:could not get lock /var/lib/dpkg/lock -ope
    YAML-CPP
    [gazebo-1] process has died [pid 22855, exit code 255,
    gperftools对程序进行分析
    pclConfig.cmake or PCLConfig.cmake
  • 原文地址:https://www.cnblogs.com/bmbi/p/5281657.html
Copyright © 2020-2023  润新知