Time (s): ~0.030
package margusmartseppcode.From_40_to_49;
public class Problem_46 {
/** Call only if: (n>0&&(i%2==0||i%3==0||i%5==0||i%7==0)) */
static boolean isPrimeS(final int n) {
final int r = (int) Math.floor(Math.sqrt(n));
for (int f = 5; f <= r; f += 6)
if (n % f == 0 || n % (f + 2) == 0) return false;
return true;
}
/** Will return array with first nr primes */
static int[] getPrimes(int nr) {
if (nr < 0) return new int[0];
int amount = 0;
int result[] = new int[nr];
if (nr > 0) result[amount++] = 2;
if (nr > 1) result[amount++] = 3;
if (nr > 2) result[amount++] = 5;
if (nr > 3) result[amount++] = 7;
if (nr <= 4) return result;
for (int i = 9;; i += 2) {
if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) continue;
if (isPrimeS(i)) {
result[amount++] = i;
if (amount >= nr) break;
}
}
return result;
}
public static void main(String[] args) {
double tmp = 0;
int i = 0, num = 3, p[] = getPrimes(1000);
for (i = 0; !(p[i] > num); i++, tmp = Math.sqrt((num - p[i]) / 2))
if (tmp == Math.ceil(tmp)) {
i = 0;
num += 2;
}
System.out.println(num);
}
}
Time (s): ~0.038
package margusmartseppcode.From_40_to_49;
import java.util.ArrayList;
import java.util.BitSet;
public class Problem_46 {
/** Sieve of Eratosthenes */
static Integer[] getSoE(int max) {
if (max < 1) return new Integer[0];
BitSet sieve = new BitSet(max / 2);
ArrayList<Integer> list = new ArrayList<integer>();
if (max > 1) list.add(2);
if (max > 2) list.add(3);
for (int i = 5, f = 1; i <= max; i += 3 - f, f = -f)
if (sieve.get(i >> 1) == false) {
for (int add, j = i + (add = i << 1); j < max; j += add)
sieve.set(j >> 1, true);
list.add(i);
}
return list.toArray(new Integer[0]);
}
public static void main(String[] args) {
double tmp = 0;
int i = 0, num = 3;
Integer p[] = getSoE(10000);
for (i = 0; !(p[i] > num); i++, tmp = Math.sqrt((num - p[i]) / 2))
if (tmp == Math.ceil(tmp)) {
i = 0;
num += 2;
}
System.out.println(num);
}
}
No comments:
Post a Comment