A sparse hair, wearing a plaid shirt middle-aged man came in, put his hand on the table of MAC, said to me: "I will record the interview process with the computer, you do not mind ah."
I replied: "Never mind."
Interviewer: "first come basis it a little arithmetic problem, write a method in Java, find prime numbers within a million."
I was thinking to myself really basic, is not a prime number except 1 and itself and can not be other external number divisible thing, so they wrote:
public static List<Integer> findPrime(){
List<Integer> list = new ArrayList<>(100000);
for (int n = 2; n < 1000000; n++) {
boolean isPrime = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
list.add(n);
}
}
return list;
}
Welcome attention to micro-channel public number: Wan Cat Society , a shared Java technology dry every week.
The interviewer frowned and said: "? Calculation divisible when the need has been calculated from 2 to n-1 Well"
After such a reminder, I suddenly remembered divisible to calculate the square root of it, then immediately modified the code:
public static List<Integer> findPrime(){
List<Integer> list = new ArrayList<>(100000);
for (int n = 2; n < 1000000; n++) {
boolean isPrime = true;
int sqrt = (int) Math.sqrt(n);
for (int i = 2; i <= sqrt; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
list.add(n);
}
}
return list;
}
Welcome attention to micro-channel public number: Wan Cat Society , a shared Java technology dry every week.
The interviewer looked at, said:. "? He is very well written, function basically realized, but think again, what can optimize the place."
I thought, said: "? It seems nothing can be optimized"
I much thought about it, he said:. "It should not have it."
The interviewer said: "OK not a thing?"
I answered yes: "OK gone."
Interviewer: "Well, hang onto this problem."
I am not convinced, rushing asked: "Do you talk about, what else can optimize the place?"
The interviewer smiled and said:. "Before computing can also take advantage of a prime number is divisible by doing it, you can at least double the performance."
Interviewer on I wrote the code changed a few strokes, it becomes:
public static List<Integer> findPrime(){
List<Integer> list = new ArrayList<>(100000);
for (int n = 2; n < 1000000; n++) {
boolean isPrime = true;
int sqrt = (int) Math.sqrt(n);
for (Integer i : list) {
if (n % i == 0) {
isPrime = false;
break;
}
if (i > sqrt) {
break;
}
}
if (isPrime) {
list.add(n);
}
}
return list;
}
Welcome attention to micro-channel public number: Wan Cat Society , a shared Java technology dry every week.
I was enlightened, this interview is really learned.
This story is purely fictitious and any similarity is just coincidence.
Welcome attention to micro-channel public number: Wan Cat Society , a shared Java technology dry every week.