java - 数组中元素的组合,用于获取数字的因子

标签 java combinations

我想要一个组合算法,...将数组中的元素乘以除其本身之外的所有其他元素...

请帮我组合例如::{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/

相关文章:

java - MVVM + 数据绑定(bind) + View 模型不更新 View

java - 如何将调用对象方法的 JSP servlet 转换为 JSTL?

java - 在这种情况下如何有效地使用线程?

python - 从 n 个整数列表(可能长度不等)中进行所有可能的 n 长度排列

python-3.x - 如何获得字符串(元音或辅音)的组合?

python - 如何使用向后组合迭代拆分字符串?

java - CXF wsdl2java 不解析目录

java - 如何将图像放在android中另一个图像上方的中央?

python - 从 python 中的列表列表创建列表的所有组合

java - 以不同的方法将操作附加到 Stream 是一种不好的做法吗?