zoukankan      html  css  js  c++  java
  • 1020. 分解质因数——java

    Description

    每一个大于等于2的自然数,均可写成一个或多个质数的乘积,例如:

    2=2
    
    20=2*2*5
    

    这种将一个整数分割成若干个质数之积的操作叫做分解质因数。现在,给你一个整数N,请你编写一个程序,对其分解质因数。

    Input Format

    输入为一行,正整数N,保证1<N<2147483647

    Output Format

    输出N的质因数分解形式,格式为 N=P1(E1)P2(E2)P3(E3).... 其中,P1、P2、P3、……为组成N的各个质因子,

    满足P1 < P2 < P3 < ...;E1、E2、E3、……分别为P1、P2、P3、……在N中的指数。

    例如:

    20=2*2*5
    

    应该输出成:

    20=2(2)5(1)
    

    Hint

    N的大于sqrt(N)的质因子至多有一个。(sqrt(n)指N的开方取整)

    Sample Input

    20
    

    Sample Output

    20=2(2)5(1)

    这道题其实思路很简单,就是找一个数的质因数,然后保存起来,最后排序并计数、、输出

    代码如下:

     1 import java.util.ArrayList;
     2 import java.util.Arrays;
     3 import java.util.Scanner;
     4 
     5 public class Main {
     6 
     7     
     8     private static Scanner in;
     9 
    10     public static void main(String[] args) {
    11         in = new Scanner(System.in);
    12         int n =in.nextInt();
    13         int a=n;
    14         int t=1;
    15         ArrayList <Integer>list=new ArrayList<Integer>();
    16         boolean flag=false;
    17         for(int i=0;i<=n;){
    18             flag=false;
    19             for(int j=2;j<=n;j=2*t-1){
    20                 if(n%j==0){
    21                     list.add(j);
    22                     flag=true;
    23                     n = n/j;
    24                     break;
    25                 }
    26                 t++;
    27             }
    28             t=1;
    29             if(!flag){
    30                 break;
    31             }
    32             i=0;
    33         }    
    34         Arrays.sort(list.toArray());
    35         int s=list.get(0);
    36         int count =0;
    37         String str="";
    38         String string="";
    39         for(int i=0;i<list.size();i++){
    40             if(list.get(i)==s){
    41                 count++;
    42                 str =string+s+"("+count+")";
    43             }else{
    44                 string=str;
    45                 count=1;
    46                 s=list.get(i);
    47                 str =string+s+"("+count+")";
    48             }
    49         }
    50             System.out.println(a+"="+str);
    51     }
    52 }

    就这样这道题解决了,但是1和0会有报错,所以可以思考一下完整的解决方案。其实很简单只需要

                            if(!flag){
    				if(n==0||n==1){
    					list.add(n);
    				}
    				break;
    			}
    

      

  • 相关阅读:
    day25:接口类和抽象类
    vue1
    How the weather influences your mood?
    机器学习实验方法与原理
    How human activities damage the environment
    Slow food
    Brief Introduction to Esports
    Massive open online course (MOOC)
    Online learning in higher education
    Tensorflow Dataset API
  • 原文地址:https://www.cnblogs.com/969059506-java/p/3801283.html
Copyright © 2011-2022 走看看