题目:将一个正整数分解质因数。例如:输入90,打印出90 = 2 * 3 * 3 * 5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
注:这里我把方法都写在MyMath的工具类里
/*
*this function returns a list that contains all prime factors
*into which the number of input can be decomposed
*/
public static List<Integer> getPrimeFactors(int number){
List<Integer> primeFactorList = new ArrayList<>();
int loop = number;
for(int i=2;i<=loop;i++){
if(isPrime(i)){
while(!hasRemainder(number,i)){
primeFactorList.add(i);
number = number/i;
}
}
}
return primeFactorList;
}
/*
* check if a number is a prime number or not
*/
public static boolean isPrime(int number){
if(number <= 1)
return false;
if(number == 2 || number ==3)
return true;
//a number more than 5 and not border upon 6 must not be a prime nunber
if( (number % 6 !=1) && (number % 6 != 5))
return false;
//here all numbers are adjacent to 6
for(int i=5;i<=Math.sqrt(number);i=i+6){
if(number%i ==0 || number%(i+2) == 0)
return false;
}
//the rest are all prime numbers
return true;
}
/*
* check if a divided by b has no remainder or not
* @param a
* the number to be divided or the dividend
*@param b
* divisor
*/
public static boolean hasRemainder(int a, int b){
if(a < b || b == 0)
return true;
if(a % b == 0)
return false;
return true;
}
测试:
public static void main(String[] args){
System.out.println(MyMath.getPrimeFactors(35));
System.out.println(MyMath.getPrimeFactors(100));
System.out.println(MyMath.getPrimeFactors(256));
System.out.println(MyMath.getPrimeFactors(101));
}
结果:
[5, 7]
[2, 2, 5, 5]
[2, 2, 2, 2, 2, 2, 2, 2]
[101]
不过,以上函数只能分解Integer.MAX_VALUE()以下的正整数。