Finding factors of a given integer

前端 未结 14 1372
终归单人心
终归单人心 2020-12-16 19:52

I have something like this down:

int f = 120;
for(int ff = 1; ff <= f; ff++){
    while (f % ff != 0){            
}

Is there anything w

14条回答
  •  孤城傲影
    2020-12-16 20:03

    public class Solution {
        public ArrayList allFactors(int a) {
    
            int upperlimit = (int)(Math.sqrt(a));
            ArrayList factors = new ArrayList();
            for(int i=1;i <= upperlimit; i+= 1){
                if(a%i == 0){
                    factors.add(i);
                    if(i != a/i){
                        factors.add(a/i);
                    }
                }
            }
            Collections.sort(factors);
            return factors;
        }
    }
    

    The above solution simply works like calculating prime factors. The difference being for every prime factor we keep calculating the other part of the product i.e the reqd number.

提交回复
热议问题