算法-java实现
1. 质因数分解
public static List<Integer> factorize(int n){ List<Integer> factors = new ArrayList(); int i; boolean isPrime = true; for (i = 2; i <= Math.sqrt(n); i++){ if (n % i == 0){ factors.add(i); isPrime = false; break; } } if (isPrime){ factors.add(n); }else{ factors.addAll(factorize( n / i)); } return factors; }
2.题目:求s = a + aa + aaa + aaaa + aa...a的值,其中a是一个数字。例如2 + 22 + 222 + 2222 + 22222(此时共有5个数相加),
解法1:非递归解法
public static int f2(int a, int n){ int s = 0; int an = 0; for (int i = 1; i <= n; i++){ an += a * Math.pow(10, n-1); s += an; } return s; }
解法2:递归解法
// g = aa...a public static int g(int a, int n){ if (n > 1){ return g(a, n -1) + a * (int)Math.pow(10, n-1); }else if ( n == 1){ return a; }else { throw new RuntimeException(); } } //f = a + aa + aaa + aaaa + aa...a public static int f(int a, int n){ if (n > 1){ return f(a, n -1) + g(a,n); }else if ( n == 1){ return a; }else { throw new RuntimeException(); } }