Java经典算法40题 – 题目4
【程序4】题目:
将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
思路:对于一个数字num,从2到num/2+1逐个判断当前数字是否是质数、且当前数字能否被num整除,如果条件都满足,则此数字就是一个质因数,则num=num/i,然后在从i到num/2+1继续判断,直到结束。
package org.sixlab.algorithm40;
public class PrimeFactor {
public static void main(String\[\] args) {
int num = 34;
System.out.println(decompose(num));
}
private static String decompose(int num) {
String result = String.valueOf(num) + " = ";
int endNum = (int) (num/2 + 1);
for (int i = 2; i < endNum; i++) {
if (isPrime(i) && isDivisible(num, i)) {
result += (i + " * ");
num /= i;
i--;
}
}
result = result.substring(0, result.length() - 3);
return result;
}
private static boolean isPrime(int num) {
if (num == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(num) + 1; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static boolean isDivisible(int num, int num2) {
if (num2 != 0 && num % num2 == 0) {
return true;
} else {
return false;
}
}
}