算法-java实现
2024-08-28 22:50:17
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();
}
}
最新文章
- Nodejs windows的安装
- linux根文件系统制作
- Modify textures at runtime
- cocos2d-x 小技巧
- linux 用grep匹配横线
- windows2008 R2 安装wampserver
- php单词里的大写字母
- sign starfieldtech
- Please ensure that adb is correctly located at &#39;...adb.exe&#39; and can be executed.
- golang实现udp接入服务器
- UI 公钥加密
- eclipse xml自动提示
- Microsoft CRM-QueryExpression 成员
- Tomcat PermGen space的解决方案
- 大数据量下的集合过滤—Bloom Filter
- Java并发编程:JMM (Java内存模型) 以及与volatile关键字详解
- js 获取属性名称
- vue中解决跨域问题
- Android Exception Type ";share_dialog_title"; is not translated in en, zh-rTW strings
- kibana 的search 的的搜索提示挡住输入框