[color=green] 分解质因数:如90=2*3*3*5,代码如下:[/color]
[color=green] 当输入108时,运行结果如下:[/color]
package com.flyingh.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个正整数:");
int n = Integer.parseInt(br.readLine());
System.out.println(n + "=" + getOut(n));
}
private static StringBuilder sb = new StringBuilder();
private static String getOut(int n) {
if (!isPrime(n)) {
for (int i = 2; i < n; i++) {
if (isPrime(i) && n % i == 0) {
sb.append(i).append("*");
return getOut(n / i);
}
}
} else {
sb.append(n);
}
return sb.toString();
}
private static boolean isPrime(int n) {
// TODO Auto-generated method stub
if (n == 1) {
throw new IllegalArgumentException("参数不能为1");
}
if (n == 2 || n == 3) {
return true;
}
for (int j = 2; j <= Math.sqrt(n); j++) {
if (n % j == 0) {
return false;
}
}
return true;
}
}
[color=green] 当输入108时,运行结果如下:[/color]
108=2*2*3*3*3