package margusmartseppcode.From_10_to_19;
import java.util.BitSet;
public class Problem_10 {
/** Sieve of Eratosthenes sum */
static long getSoEsum(int max) {
if (max < 1)
return 0;
BitSet sieve = new BitSet(max / 2);
long sum = (max > 1 ? 2 + (max > 2 ? 3 : 0) : 0);
for (int i = 5, f = 1; i <= max; i += 3 - f, f = -f)
if (sieve.get(i >> 1) == false) {
int add = i << 1;
for (int j = i + add; j < max; j += add)
sieve.set(j >> 1, true);
sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(getSoEsum(2000000));
}
}
Showing posts with label BitSet. Show all posts
Showing posts with label BitSet. Show all posts
Tuesday, September 8, 2009
Euler Problem 10 solution
Time (s): ~0.097
Euler Problem 7 solution
Time (s): ~0.011
package margusmartseppcode.From_1_to_9;
import java.util.BitSet;
public class Problem_7 {
static long getSoExnt(int max, int nr) {
if (max < 1 || nr < 1 || max < nr)
return -1;
if (nr < 4)
return (nr == 1 ? 2 : (nr == 2 ? 3 : 5));
BitSet sieve = new BitSet(max / 2);
for (int i = 5, f = 1, c = 2; i <= max; i += 3 - f, f = -f)
if (sieve.get(i >> 1) == false) {
int add = i << 1;
for (int j = i + add; j < max; j += add)
sieve.set(j >> 1, true);
if (++c >= nr)
return i;
}
return -1;
}
public static void main(String[] args) {
System.out.println(getSoExnt(120000, 10001));
}
}
Subscribe to:
Posts (Atom)