查找给定整数的因子

编程入门 行业动态 更新时间:2024-10-07 14:22:32
本文介绍了查找给定整数的因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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.

更多推荐

查找给定整数的因子

本文发布于:2023-11-29 09:11:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645967.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   因子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!