我想要一个组合算法,...将数组中的元素乘以除其本身之外的所有其他元素...
请帮我组合例如::{1,2,3,4,5,6}
输出::1*2,1*3....1*6, 1*2*3!*2*4.......1*2*3*4*5*6。 ……5*6
代码已删除,它与我的问题的逻辑要求无关......
最佳答案
我相信这就是您正在寻找的:
//This method return a list of lists, where each "inner list" contains as
//its first number the number for which the factors are being found, and
//every other number is a factor.
//It takes an array of all the numbers whose factor you wish to find
public List<List<Integer>> getAllFactors(int[] toCalculate){
List<List<Integer>> toReturn = new ArrayList<List<Integer>>();
List<Integer> factors;
for(int i = 0; i < toCalculate.length; i++){
factors = new ArrayList<Integer>();
factors.add(toCalculate[i]); //add the number whose factors will be calculated
//the square root is used because it is the largest number you can divide by without getting "overlap"
for(int j = 1; j <= Math.sqrt(toCalculate[i]); j++){
if(toCalculate[i]%j==0){ //if it divides evenly, add it
factors.add(j);
factors.add((Integer)toCalculate[i]/j); //also add its "partner" number
}
}
toReturn.add(factors);
}
return toReturn;
}
我放入类Test
...这是我的测试方法:
public static void main(String[] args){
Test t = new Test();
List<List<Integer>> blah = t.getAllFactors(new int[]{10, 12, 1, 5});
for(List<Integer> i: blah)
System.out.println(Arrays.toString(i.toArray(new Integer[i.size()])));
}
我意识到这不是问题所要求的...我想...我真的不能说... 不管怎样,我写了一个替代方法:
public List<Integer> getAllFactors(int number){
List<Integer> factors = new ArrayList<Integer>();
for(int i = 2; i <= Math.sqrt(number); i++){
if(number%i==0){
factors.add(number);
factors.addAll(getAllFactors(i));
factors.addAll(getAllFactors(number/i));
}
}
if(factors.isEmpty())
factors.add(number);
return factors;
}
但后来我意识到这可能也不是你想要的。事实是,我实际上不知道你在寻找什么,我无法理解你的帖子。我刚刚试图从评论中收集信息。
关于java - 数组中元素的组合,用于获取数字的因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6707576/