2009-01-11, 10:40 PM (This post was last modified: 2009-01-12, 01:16 AM by KajitiSouls.)
Quote:The first four primes for which any two primes concatenate to produce another prime is 3, 7, 109, 673. For example, if you concatenate 7 and 109, you'll get the prime 7109, and concatenating 109 and 7 yields the prime 1097. The sum of these four primes is 792, and is the lowest sum for the set of four primes with this property.
Find a set of five primes for which any two primes concatenate to produce another prime, and has the lowest sum of such sets of five primes.
--You may use any programming language.
--The script must be written in a fashion that there are no other assumptions made about the nature of the problem without reasonable proof. For example, you may not assume that the highest prime number is below 1,000,000.
--The script execution time preferably produces the answer in under 1 minute for modestly powered computers.
--You may use Google or any other resource to help you. (so long as you don't cheat and look up the answer!)
This is a math problem meant for programming practice. The main problem I'm having is getting the execution time to below 1 minute, but I'm not sure how I can make my algorithm more efficient. Heck, it actually stops when it finds the first set of 5 primes, and it doesn't really check whether it has the lowest sum of all sets of 5 primes. About the only thing I can think of right now is avoiding redundant checks when trying to find larger sets of primes. If anyone has any crazy tips that I don't know about, please feel free to share =)
Java algorithm
Code:
import java.util.*;
public class Project60 {
//Find a set of five primes for which any two primes concatenate to produce another
//prime.
//Hashtable of primes contains keys whose values are determined to be prime.
private static Hashtable<Long, Boolean> primesTable = new Hashtable<Long, Boolean>();
//List of primes, whose values are in order.
private static ArrayList<Long> primesList = new ArrayList<Long>();
//List of two primes that concatenate to produce primes.
private static ArrayList<long[]> primesListTwo = new ArrayList<long[]>();
//List of three primes that concatenate to produce primes.
private static ArrayList<long[]> primesListThree = new ArrayList<long[]>();
//List of four primes that concatenate to produce primes.
private static ArrayList<long[]> primesListFour = new ArrayList<long[]>();
//Algorithm starts by determining the new prime number to compare to existing known sets
//of primes, if determined. Each set of primes is checked for compatibility every
//cycle. It should be noted that the prime numbers 2 and 5 are excluded since
//they will NEVER form prime numbers if concatenated last.
public static void main(String[] args){
primesList.add(3L);
long nextPrime = 5; //the new prime number that gets compared with every cycle
boolean isCompatible = true;
double time = System.currentTimeMillis();