将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
public class PrimeFactorDemo { ?? ?private final static int START_FACTOR = 2;
?? ?public void printPrimeFactor(int i) { ?? ??? ?int factor = START_FACTOR; ?? ??? ?System.out.print(i + "="); ?? ??? ?int leftNum = i; ?? ??? ?while (factor <= Math.sqrt(leftNum)) { ?? ??? ??? ?if (leftNum % factor == 0) { ?? ??? ??? ??? ?leftNum = leftNum / factor; ?? ??? ??? ??? ?System.out.print(factor + "*"); ?? ??? ??? ??? ?factor = START_FACTOR; ?? ??? ??? ??? ?continue; ?? ??? ??? ?} else { ?? ??? ??? ??? ?factor++; ?? ??? ??? ?} ?? ??? ?} ?? ??? ?if (leftNum < i) { ?? ??? ??? ?System.out.print(leftNum); ?? ??? ?} else { ?? ??? ??? ?System.out.println("不可分解质因数"); ?? ??? ?} ?? ?}
?? ?public static void main(String[] args) { ?? ??? ?PrimeFactorDemo demo = new PrimeFactorDemo(); ?? ??? ?demo.printPrimeFactor(90); ?? ?} }
|