So, I began this challenge on CodeEval, which asks to print out the number of prime numbers less than any given integer N, where 0 < N < 4,294,967,295, ideally in O(N log N) time. I came up with this solution:
import java.io.*;
public class Main {
public static void main (String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
int limit;
while ((line = buffer.readLine()) != null) {
StringBuilder sb = new StringBuilder();
line = line.trim();
limit = Integer.valueOf(line);
for (int i = 2; i <= limit; i++)
if (isPrime(i) || i == 2)
sb.append(i + ",");
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
}
}
private static boolean isPrime(int n) {
if (n % 2 == 0)
return false;
for (int i = 3; i*i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
}
Basically, I'm building up a string where I append all prime numbers less than N (which is passed by argument). Testing it, it works perfectly (or so it seems); submitting it, I get a "partially" status and score of 85. Don't know really what I'm messing up here...
N
, it can be done inO(Sqrt(N) log(Sqrt(N))
. \$\endgroup\$