I have created a program to extract prime numbers from numbers from 1 million to 1 million, and I would like to use the installed processor as much as possible to reduce processing time.
int core=Runtime.getRuntime().availableProcessors();
may help, but I don't know how to incorporate it.Could you please let me know which programs and sites you would like to refer to?
public class prime number {
public static void main(String[]args) {
intu = 0;
long startTime = 0;
longestimatedTime = 0;
System.out.println("Prime number counting started";
startTime = System.nanoTime();
r:
for(inti=2;i<=100000;i++){
for(int j=2;j<i;j++){
if(i%j==0)continuer;
}
u++;
System.out.print(i+"");
}
estimatedTime=System.nanoTime()-startTime;
System.out.println("Started time:"+startTime);
System.out.println("Complete.Time:"+estimatedTime);
System.out.println("Number of prime number:"+u);
}
}
Create a method for determining prime numbers and
static boolean isPrime (int number) {
if(number<=2)
return number == 2;
else
US>return(number %2)!=0
&IntStream.rangeClosed(3,(int)Math.sqrt(number))
.filter(n->n%2!=0)
.noneMatch(n->(number%n==0));
}
Calling with Stream API should automatically parallelize and reduce processing time.
IntStream.range(1100000).parallel().filter(primenumber::isPrime)
.forEach(i->System.out.print(i+""));
Remove .parallel()
if you want to ensure the order.
As a result of my hand measurement, the processing time has been reduced from approximately 3 seconds to approximately 0.4 seconds.
© 2024 OneMinuteCode. All rights reserved.