Solution
To start, we will just copy the prime generation function from past problems
void fill_primes(std::vector<int>& a, int count) {
a.clear();
a.reserve(count);
for (int candidate = 2; a.size() < static_cast<std::size_t>(count);
++candidate) {
bool prime = true;
for (int p : a) {
if (p > candidate / p) break;
if (candidate % p == 0) {
prime = false;
break;
}
}
if (prime) {
a.push_back(candidate);
}
}
}
Next, have a method to check if three numbers are permutations of each other
bool are_permutations(int a, int b, int c) {
int b_counts[10] = {};
int c_counts[10] = {};
do {
++b_counts[a % 10];
++c_counts[a % 10];
a /= 10;
} while (a > 0);
do {
--b_counts[b % 10];
b /= 10;
} while (b > 0);
do {
--c_counts[c % 10];
c /= 10;
} while (c > 0); d
for (int digit = 0; digit < 10; ++digit) {
if (b_counts[digit] != 0 || c_counts[digit] != 0) {
return false;
}
}
return true;
}Finally, I did this the naive way. First filter out all the 4 digit primes and then in a triple loop, check if their difference matches and if they’re permutations of each other
for (int i = 0; i < four_digits.size(); i++) {
for (int j = i+1; j < four_digits.size(); j++) {
for (int k = j+1; k < four_digits.size(); k++) {
if (four_digits[j]-four_digits[i] == four_digits[k]-four_digits[j]) {
if (are_permutations(four_digits[i], four_digits[j], four_digits[k])) {
printf("%d, %d %d are permutations \n", four_digits[i], four_digits[j], four_digits[k]);
}
}
}
}
}