【问题标题】:Output breaks as input parameter increase in size随着输入参数大小的增加,输出中断
【发布时间】:2015-08-18 07:57:50
【问题描述】:

我正在编写一个基本程序,它接受一个参数,然后根据该参数计算奇数的乘积。

如果我传递从 1 到 19 的任何值,但在 20 时我的输出是负数,而在 35 时它是 0??

我确定算法有问题?

建议:

import java.util.ArrayList;
import java.util.List;


public class ProductOfIntegers {

public static void productOfOddIntegers(int i){
    int[] numbers = new int[i];
    for(int j = 0; j < numbers.length; j++){
        numbers[j] = j + 1;
    }
    List<Integer> oddNumbers = new ArrayList<Integer>();
    for(int j = 0; j < numbers.length; j++){

        if(numbers[j] % 2 != 0){
            oddNumbers.add(numbers[j]);
        }
    }       
    int product = 1;
    for(int n: oddNumbers)
        product*=n;
    System.out.println(oddNumbers); 
    System.out.println(product);

}

public static void main(String [] args){
    productOfOddIntegers(15);
}

}

【问题讨论】:

  • 不是你的问题的答案,但if(numbers[j] % 2 == 0) 得到偶数。
  • int 的最大值是多少? 1 * 3 * ... * 21 的值是多少?
  • @Evan Frisch - 感谢您指出这一点。我总是把那些搞混了!在编辑中修复它。
  • 使用 long 或 BigInteger。顺便说一句,不需要存储所有数字,只需遍历奇数并根据需要相乘
  • @JB Nizet 如果我超过最大值,为什么它会在输出中变为负数?

标签: java arrays conditional-statements


【解决方案1】:

根据该参数计算奇数个数的乘积。

您的程序不会计算偶数的乘积。

话虽如此,您的算法效率相当低:您可以简单地使用单个 for 循环,而不是首先生成一个整数数组,然后过滤并最终计算产品:

public static long productOfOddIntegers(int n){
    long prod = 1;
    for(int i = 3; i <= n; i += 2) {
        prod *= i;
    }
    return prod;
}

您最好使用long,因为此类产品可能相当庞大。毕竟,这与阶乘的根成比例。

您还可以使用BigInteger 方法,您可以使用任意n

public static BigInteger productOfOddIntegers(int n){
    BigInteger prod = BigInteger.ONE;
    BigInteger bin = new BigInteger(""+n);
    BigInteger two = BigInteger.ONE.add(BigInteger.ONE);
    for(BigInteger i = two.add(BigInteger.ONE); i.compareTo(bin) <= 0; i = i.add(two)) {
        prod = prod.multiply(i);
    }
    return prod;
}

jdoodle demo

在方法中执行println 命令也是糟糕的设计。您应该在 calculatingprinting 之间进行区分。

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2018-06-28
    • 2020-09-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多