Java 8流查找许多因素

时间:2018-08-25 13:50:11

标签: java java-8 runtime-error

我陷入了以下问题,使用Java 8流找到给定数量的因子数量。虽然在codechef中提交解决方案,但其中一个子任务被接受,但其他所有子任务都抛出了NZEC,而解决方案却没有公认。 我尝试将代码包装在try / catch块中,但仍然得到NZEC作为输出。

import java.util.Scanner;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int testCases = scanner.nextInt();
        while (--testCases >= 0) {
            int nValue = scanner.nextInt();
            int product = 1;
            while (nValue-- != 0) {
                int currentVal = scanner.nextInt();
                product *= currentVal;
            }
            int prod = product;
            System.out.println(Stream.iterate(2, x -> x + 1).limit(prod / 2).filter(num -> prod % num == 0).count() + 2);
        }
    }
}

我对竞争性编码真的很陌生,无法找出上述代码的问题。请帮忙...。

1 个答案:

答案 0 :(得分:0)

一些可能引起问题的东西

  • int使用product可能会溢出(超过Integer.MAX_VALUE),尤其是在乘法运算中。这可能会导致product的值为负,而给您IllegalArgumentException为负的limit()。您应该切换到long

  • 限制应为Math.ceil(sqrt(product))

  • 您不应乘以,计算单独的currentValue的因数并将结果相加会更快。

相关问题