I am a student studying IT in an University. I’ve been giving an assignment of searching for prime numbers above one quadrillion. Steps have been given:
-
Start number as one quadrillion
-
Select odd-numbered candidates
-
Divide them by every odd integer between 3 and their square root. if
one of the integers evenly divides the candidate, it’s declared
prime.
Now this is what i’ve come up with :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PrimeSearcher extends HttpServlet{
private long number = 10000000000000001L;
private boolean found = false;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
PrintWriter out = response.getWriter();
while(!checkForPrime(number)){
number = number+2;
}
if(found){
out.println("The first prime number above 1 quadrillion is : " + number);
}
}
public boolean checkForPrime(long numberToCheck){
double sqrRoof = Math.sqrt(numberToCheck);
for(int i=3; i< sqrRoof; i++){
if(numberToCheck%i==0){
return false;
}
}
found= true;
return found;
}
}
My worry is that am not sure whether am on the right path and another issue is that this always one number ,the first one. after googling i found that on servlet.com and javafaq that they are using thread and i’ve run theirs and it seem to be cool. I don’t really understand that one but it gives different numbers.
So I am now confused right now about how to implement that algorithm and i really don’t want to copy that one. Maybe after understanding their method i can code this algorithm better.
Thanks
I think it looks OK, but you might need the
iincheckForPrimeto be alongtype. And you’re not incrementingiby 2 (you only need to check for odd divisors).Just be prepared for this to take a long time…….