题目:质因数分解
题目说明:
请设计一程式,输入一个正整数,改用质因数乘积表达此数,若该质因数出现多次,则用次方表示之。
例如:
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)); } }