gpt4 book ai didi

java - 查找给定整数的因子

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:15 26 4
gpt4 key购买 nike

我有这样的东西:

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

我的循环查找因子有什么问题吗?对于 for 和 while 语句的工作原理,我真的很困惑,所以它们很可能是完全错误的。

在此之后,我将如何为上述因素分配变量?

最佳答案

以下代码将返回给定数字的所有因数列表:

public ArrayList<Integer> findFactors(int num) {        
ArrayList<Integer> factors = new ArrayList<Integer>();

// Skip two if the number is odd
int incrementer = num % 2 == 0 ? 1 : 2;

for (int i = 1; i <= Math.sqrt(num); i += incrementer) {

// If there is no remainder, then the number is a factor.
if (num % i == 0) {
factors.add(i);

// Skip duplicates
if (i != num / i) {
factors.add(num / i);
}

}
}

// Sort the list of factors
Collections.sort(factors);

return factors;
}

这个答案改进了 Sharad Dargan's answer有两种方式:

  1. 基于 this answer 中使用的想法,您可以根据数字是偶数还是奇数来确定要递增的值,从而加快求解速度。

    在for循环之前添加如下代码行:

    int incrementer = num % 2 == 0 ? 1 : 2;

    然后将循环的最后一部分更改为:

     i += incrementer

    如果数字是奇数,它将跳过所有偶数,而不是无论如何总是递增 1。

  2. Sharad 将上限值存储在一个变量中,然后在 for 循环中使用该变量:

    int upperlimit = (int)(Math.sqrt(a));
    ...
    for(int i = 1; i <= upperlimit; i+= 1)

    相反,将 Math.sqrt(num) 直接放在 for 循环中并跳过上限变量:

    for (int i = 1; i <= Math.sqrt(num); i += incrementer) {

    这将允许您跳过代码的转换部分,创建更清晰的代码。


然后您可以使用一些 JUnit 测试用例:

@Test
public void test12() {
FindFactors find = new FindFactors();

int num = 12;
List<Integer> factors = Arrays.asList(1, 2, 3, 4, 6, 12);

assertEquals(factors, find.findFactors(num));
}

@Test
public void test1000000() {
FindFactors find = new FindFactors();

int num = 1000000;
List<Integer> factors = Arrays.asList(1, 2, 4, 5, 8, 10, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200,
250, 320, 400, 500, 625, 800, 1000, 1250, 1600, 2000, 2500, 3125, 4000, 5000, 6250, 8000, 10000, 12500,
15625, 20000, 25000, 31250, 40000, 50000, 62500, 100000, 125000, 200000, 250000, 500000, 1000000);

assertEquals(factors, find.findFactors(num));
}

@Test
public void test1() {
FindFactors find = new FindFactors();

int num = 1;
List<Integer> factors = Arrays.asList(1);

assertEquals(factors, find.findFactors(num));
}

@Test
public void test0() {
FindFactors find = new FindFactors();

int num = 0;
List<Integer> factors = new ArrayList<Integer>();

assertEquals(factors, find.findFactors(num));
}

关于java - 查找给定整数的因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com