Java의 Biginteger 가능한 프라임과 협력합니다
-
22-08-2019 - |
문제
두 숫자 사이의 모든 소수를 인쇄하고 싶습니다. 이것은 내 코드입니다.
package sphere;
import java.math.BigInteger;
import java.io.*;
class PrimeTest2 {
public static void main(String args[]) throws java.lang.Exception {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
String [] splitted = s.split(" ");
BigInteger lower = new BigInteger(splitted[0]);
BigInteger upper = new BigInteger(splitted[1]);
int lowerAsInt = Integer.parseInt(splitted[0]);
int upperAsInt = Integer.parseInt(splitted[1]);
BigInteger intermediate = lower;
for (int i=lowerAsInt; i<upperAsInt; i++) {
intermediate = intermediate.nextProbablePrime();
System.out.println(intermediate);
}
}
}
1 10으로 실행되면 출력은 다음과 같습니다.
2
3
5
7
11
13
17
19
23
왜 7시에 멈추지 않습니까?
해결책
귀하의 프로그램은 실행 시간 (1 ~ 9)이 10 세 이하로 멈추지 않기 때문에 다음과 같이 원할 것입니다.
BigIntegerupper = BigInteger.valueOf(upperAsInt);
while (intermediate.compareTo(upper) <= 0) {
System.out.println(intermediate);
intermediate = intermediate.nextProbablePrime();
}
차이를 보시겠습니까? 당신은 1에서 시작하여 9 (10 미만)에서 멈추고 각 반복에 숫자를 인쇄합니다. 위는 숫자가 상한보다 큰 경우 중지됩니다.
다른 팁
프라임의 값이 10보다 큰 경우 중지하지 않기 위해 (i <10)을 실행하도록 설정되어 있습니다.
I를 매번 증가 시키므로 i = 1에서 i = 10 (9 회)에서 실행됩니다. 이전 세트 i = 중간 세트를 중지하려면.
당신은 계산하고 있습니다 i
~에서 lowerASInt
에게 upperAsInt
. 당신은 내가 1에서 10까지 계산하고 있습니다. i++
증분 i
1 (1).
그래서 당신의 루프는 다음과 같습니다 i
10 미만, 프라임 및 증분을 인쇄하십시오. i
1.
따라서 처음 9 개의 결과를 얻을 수 있습니다.
JDK8을 사용하는 경우 작동합니다
BigInteger lower=BigInteger.valueOf(1);
BigInteger high=BigInteger.valueOf(100);
Stream.iterate(lower, BigInteger::nextProbablePrime).limit(high.longValueExact())
.filter(p -> p.compareTo(high) <= 0).forEach(System.out::println);
성능을 늦추기 때문에 위의 스트림에는 Parallel ()을 사용하지 마십시오. 코드에 stream.iterate () 또는 stream.limit ()가 있으면 스트림을 병렬화하지 마십시오. 내 VM의 간단한 벤치 마크는 병렬 버전이 반복적 인 것보다 4 배 더 느리다는 것을 보여줍니다.
제휴하지 않습니다 StackOverflow