Ad
Puzzles
Mathematics
Code
Diff
  • import java.util.Iterator;
    import java.util.TreeSet;
    class AncientPrimes {
    	public static Integer[] sumOfPrimes(int start, int end) {
    		TreeSet<Integer> primes = new TreeSet<Integer>();
    		TreeSet<Integer> result = new TreeSet<Integer>();
    		boolean[] table = new boolean[end + 1];
    		table[0] = true;
    		table[1] = true;
    
    		for (int i = start; i < table.length; i++) {
    			if (!table[i]) {
    				for (int j = i + i; j < table.length; j += i) {
    					table[j] = true;
    				}
    				int minusResult = Integer.MIN_VALUE;
    				int minus = 0;
    				Iterator<Integer> iterator = primes.descendingIterator();
    				boolean isPrime = false;
    				while (minusResult < minus && iterator.hasNext() && !isPrime) {
    					minus = iterator.next();
    					minusResult = i - minus;
    					isPrime = primes.contains(minusResult);
    				}
    
    				if (isPrime)
    					result.add(i);
    
    				primes.add(i);
    			}
    		}
    		return result.toArray(new Integer[0]);
    	}
    }
    • import java.util.Iterator;
    • import java.util.TreeSet;
    • class AncientPrimes {
    • public static Integer[] sumOfPrimes (int start, int end){
    • // To Do
    • return new Integer[0];
    • }
    • public static Integer[] sumOfPrimes(int start, int end) {
    • TreeSet<Integer> primes = new TreeSet<Integer>();
    • TreeSet<Integer> result = new TreeSet<Integer>();
    • boolean[] table = new boolean[end + 1];
    • table[0] = true;
    • table[1] = true;
    • for (int i = start; i < table.length; i++) {
    • if (!table[i]) {
    • for (int j = i + i; j < table.length; j += i) {
    • table[j] = true;
    • }
    • int minusResult = Integer.MIN_VALUE;
    • int minus = 0;
    • Iterator<Integer> iterator = primes.descendingIterator();
    • boolean isPrime = false;
    • while (minusResult < minus && iterator.hasNext() && !isPrime) {
    • minus = iterator.next();
    • minusResult = i - minus;
    • isPrime = primes.contains(minusResult);
    • }
    • if (isPrime)
    • result.add(i);
    • primes.add(i);
    • }
    • }
    • return result.toArray(new Integer[0]);
    • }
    • }