由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - [算法]打印所有因子乘积组合
相关主题
问个题的解题思路【字符指针题】求帮助?
分享:non-recursive breadth first search and depth first search algorithm in CLRU question
一道google面经难题二维数组参数怎么传好?
问个C++题发一个有趣的java题
bloomberg相关的面试题问个外循环和内问题
array of pointers to functions今天一个很怪异的面试题目
请问以下程序运行结果请教个问题,这个程序错在哪里?
max sub vector sum 问题问一个java的基本问题
相关话题的讨论汇总
话题: int话题: decompose话题: prime话题: dfs
进入JobHunting版参与讨论
1 (共1页)
d********w
发帖数: 363
1
打印一个整数的所有可能乘积组合,并按因子从大到小输出,例如
PrintFactors 12
12 * 1
6 * 2
4 * 3
3 * 2 * 2
其中4*3, 3*4是同样的,就没有必要打印了
在比如
PrintFactors 32
32 * 1
16 * 2
8 * 4
8 * 2 * 2
4 * 4 * 2
4 * 2 * 2 * 2
2 * 2 * 2 * 2 * 2
大家有什么好的方法,直观是把所有的可能(构成no1*no2字符串)都存入到hash表中用
来排重
g**********y
发帖数: 14569
2
不用那么复杂,这种题就是brutal force + DFS
public class Decompose {
private void decompose(int N) {
dfs(N, N, "");
}

private void dfs(int N, int hi, String s) {
if (N == 1) {
if (s.contains("*")) {
System.out.println(s);
}
else {
System.out.println(s + "*1");
}
return;
}

for (int i=hi; i>1; i--) {
if (N%i == 0) {
dfs(N/i, i, s.length()==0? s+i : s+"*"+i);
}
}
}

public static void main(String[] args) {
new Decompose().decompose(1024);
}
}
s*******f
发帖数: 1114
3
int GetNextPrime(){ // substitute this with more excellent algorithm
static int primes[] = {2,3,5,7,11};
static int idx = 0;
return primes[idx++];
}
void PrintFactors(int n){
if (n < 0){
n = -n;
}
if (n == 0){
return;
}
int prime = 1;
while (prime <= sqrt(double(n))){
prime = GetNextPrime();
while (n % prime == 0){
printf("%d ", prime);
n /= prime;
}
}
if (n > 1){
printf("%d ", n);
}
}

【在 d********w 的大作中提到】
: 打印一个整数的所有可能乘积组合,并按因子从大到小输出,例如
: PrintFactors 12
: 12 * 1
: 6 * 2
: 4 * 3
: 3 * 2 * 2
: 其中4*3, 3*4是同样的,就没有必要打印了
: 在比如
: PrintFactors 32
: 32 * 1

1 (共1页)
进入JobHunting版参与讨论
相关主题
问一个java的基本问题bloomberg相关的面试题
返回字符串所有的 combinationarray of pointers to functions
网上很多blog show算法结果是个错的作者压根没验证过请问以下程序运行结果
讨论一道题:找出一个board上的所有单词max sub vector sum 问题
问个题的解题思路【字符指针题】求帮助?
分享:non-recursive breadth first search and depth first search algorithm in CLRU question
一道google面经难题二维数组参数怎么传好?
问个C++题发一个有趣的java题
相关话题的讨论汇总
话题: int话题: decompose话题: prime话题: dfs