SuperPrime Rib
Algorithm
1) First search for primes of length 1.
2) Add one digit to the found primes to find primes of length 2.
3) Repeat until all primes of length n have been found.
C++
#include <cstdio>
#include <vector>
#include <fstream>
#include <math.h>
#include <algorithm>
using namespace std;
bool isPrime(int num){
if(num == 0 || num == 1){ return false; }
bool k = true;
for(int f=2; f<sqrt(num)+1; f++){
if(num % f == 0){
k = false;
break;
}
}
return k;
}
void search(int n, vector<int> & res){
vector<int> primes = {2,3,5,7}; // initialize with one-digit primes
vector<int> newDigits = {1,3,7,9}; // the digits that we can add
for(int len = 2; len <= n; len++){
vector<int> newPrimes;
for(int prime:primes){
for(int d:newDigits){
int newPrime = 10*prime+d;
if(isPrime(newPrime)){
newPrimes.push_back(newPrime);
}
}
}
primes = newPrimes;
}
sort(primes.begin(),primes.end());
res = primes;
}
int main(){
// Get the length of primes we want
ifstream fIn("sprime.in");
int n;
fIn >> n;
fIn.close();
// Get the superprimes
vector<int> res;
search(n,res);
// Write primes to file
ofstream fOut("sprime.out");
for(int p:res){
fOut << p << endl;
}
fOut.close();
}