顺手写了下 整数因子分解 与 整数质因数分解
1.求整数因子分解有多少种?
2.输出整数的质因数分解
- public class Decomposition {
- public static void main(String[] args){
- int a = 12;
- int count = decomp(a);
- System.out.println(count);
- primeDecomp(72);
- }
- /**
- * 整数因子分解有多少种不同的分解方法?
- * 如12=12=6*2=4*3=3*4=3*2*2=2*6=2*3*2=2*2*3 共8种
- * 可先确定一个因子i,则种数f(n) = sum{f(n/i}|i为n的因数}
- * @param n
- * @return
- */
- private static int decomp(int n) {
- if(n==1)
- return 1;
- int result=0;
- for(int i=2;i<=n;i++)
- if(n%i==0)
- result+=decomp(n/i);
- return result;
- }
- /**
- * 整数质因数分解
- * 输出72=2^3 * 3^2 = 2*2*2*3*3
- */
- private static void primeDecomp(int n){
- while(n%2==0){
- n = n/2;
- System.out.print("2 ");
- }
- int i = 3;
- while(i<=n){
- if(isPrime(i))
- while (n % i == 0) {
- System.out.print(i + " ");
- n = n/i;
- }
- i+=2;
- }
- }
- public static boolean isPrime(int n) {
- for (int i = 2; i <= Math.sqrt(n); i++) {
- if (n % i == 0) {
- return false;
- }
- }
- return true;
- }
- }
转载于:https://blog.51cto.com/dongdong1314/413285