目前,我正试图将Java 8的Stream集成到我的日常Java工具箱中。我试图使用流来查找正整数的素因子,然后将每个因子存储在数组(或ArrayList)中,并将它们的多重性存储在并行数组中。或者,我试着创造一条.FactorWithMultiplicity对象,甚至是以因子为键、以多重性为值的Map。如果这些因素按升序排序,如果它甚至能够处理非常大的数字(比如,我敢说,Long.MAX_VALUE),那就太好了。
目前,我的代码看起来是这样的,但是,由于我是流的初学者,我确信有一种更快或更合适的方式来完成这项任务。请使用流来创建您的解决方案,尽管如果您知道一些非流解决方案更快,请随时向我指出该代码。
int num = getPositiveInt();
ArrayList<Integer> factors = new ArrayList<>();
ArrayList<Integer> multiplicities = new ArrayList<>();
boolean isPrime = IntStream.rangeClosed(2, num / 2)
.reduce(num, (int temp, int factor) -> {
int count = 0;
while (temp % factor == 0) {
temp /= factor;
count++;
}
if (count > 0) {
factors.add(factor);
multiplicities.add(count);
}
return temp;
}) > 1;发布于 2016-03-13 06:01:03
经过彻底调查后,我发现与我在问题中发布的内容相比,这是一个速度上的巨大进步。唯一速度更快的是@Misha在将他们的factors函数改为使用.rangeClosed(prevFactor, Math.sqrt(num))之后发布的。然而,另一种解决方案是最快的解决方案.期间..。但不使用溪流。
public static Map<Long, Integer> factorize(long num) { //NOW USING LONG
Map<Long, Integer> factors = new LinkedHashMap<>(); //NOW USING MAP
long lastRemainder = LongStream.rangeClosed(2, (long) Math.sqrt(num)) //NOW USING SQRT
.filter(x -> (x== 2||x%2>0)&&(x==3||x%3>0)&&(x==5||x%5>0)) //ADDED THIS
.reduce(num, (temp, factor) -> {
if (factor <= temp / factor) { //ADDED THIS
int count = 0;
while (temp % factor == 0) {
temp /= factor;
count++;
}
if (count > 0)
factors.put(factor, count);
}
return temp;
});
if (lastRemainder != num && lastRemainder > 1) //ADDED THIS
factors.put(lastRemainder, 1);
return factors;
}https://stackoverflow.com/questions/35966710
复制相似问题