查找给定整数的因子 [英] Finding factors of a given integer

查看:144
本文介绍了查找给定整数的因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的循环有什么不对吗?我对于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.

这篇关于查找给定整数的因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆