Problem Description
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
C++
This problem is interesting! I use Deep First Tradegy to resolve this problem.
const int MAX_NUM = 10000;int* g_primes = NULL;int g_length = 0;void InitPrimes(){ g_length = MAX_NUM / 5; g_primes = new int[g_length]; MakePrimes(g_primes, g_length, MAX_NUM);}struct NumberWithWeight{ int Number; int Weight; NumberWithWeight(int num, int weight) : Number(num), Weight(weight) { } NumberWithWeight() : Number(0), Weight(1) { }};NumberWithWeight* g_result = new NumberWithWeight[5];NumberWithWeight GetNumberWeight(int num){ int weight = 10; while(num / weight != 0) { weight *= 10; } return NumberWithWeight(num, weight);}bool CheckIsPrime(const NumberWithWeight& num1, const NumberWithWeight& num2){ int temp = num1.Number * num2.Weight + num2.Number; if(!IsPrime(temp)) { return false; } temp = num2.Number * num1.Weight + num1.Number; return IsPrime(temp);}map