package com.yourself.yours; import java.util.Scanner; /** *************************************************************** * @author cc Factors * 分解质因数 如: 输入90 打印 90=2*3*3*5 * 分析: 对n进行分解质因数 * 1.设定最小的质数 k=2; * 2.if k==n 说明n本身就是质因数 分解过程完成 ,直接打印 * 3.if n!=k打印k,并用n除以k的商,作为新的正整数n,重复执行第二步 * 4.if n%k != 0 则用k+1作为k的值,重复第二步 *************************************************************** */ public class Factors { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); System.out.println("please input a number of positive integer: "); int c = s.nextInt(); printFactors(c, makeFactors(c));; } private static StringBuffer makeFactors(int n) { int k = 2;// set the small factors StringBuffer strb = new StringBuffer();// save the everybody of the factors while (k <= n) { if (k == n) { strb.append(n); break; } else if (n % k == 0) { strb.append(k); n = n / k; } else { k++; } } return strb; } private static void printFactors(int clientNumber, StringBuffer factors){ for(int i = 0; i < factors.length()-1; i++){ if(i % 2 == 0){ factors.insert(i+1, "*"); } } System.out.println(clientNumber + "=" + factors); } }
时间: 2024-10-26 18:32:36