我的循环有什么不对吗?我对于for和while语句的运行感到困惑,所以很可能是完全错误的。
在这之后,我将如何去分配变量因为它是一个公共的数组,所以我们可以使用这个数组来解决这个问题。 allFactors(int a){ int upperlimit =(int)(Math.sqrt(a)); ArrayList<整数>因子= new ArrayList< Integer>(); 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(因子); 回报因素; $ b $ p $ b $ p上面的解决方案就像计算素数因子一样。 不同之处在于每个主要因素,我们继续计算产品的其他部分,即需求数量。
I have something like this down:
int f = 120; for(int ff = 1; ff <= f; ff++){ while (f % ff != 0){ }Is there anything wrong with my loop to find factors? I'm really confused as to the workings of for and while statements, so chances are they are completely wrong.
After this, how would I go about assigning variables to said factors?
解决方案 public class Solution { public ArrayList<Integer> allFactors(int a) { int upperlimit = (int)(Math.sqrt(a)); ArrayList<Integer> factors = new ArrayList<Integer>(); 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.
更多推荐
查找给定整数的因子
发布评论