#include <iostream>
#include <bitset>
#include <stdexcept>
#include <cstdlib>

using namespace std;

const int maksimum = 1000000;
const int sqrtmaks = 1000;

bitset<maksimum> sito;
bitset<maksimum> checked;

void prosij() {
    sito.set().reset(0).reset(1);
    for (int i = 2; i < sqrtmaks; ++i)
	if (sito.test(i))
	    for (int j = i + i; j < maksimum; j += i)
		sito.reset(j);
}

bool isCircPrime(int n, int b, int z, int &count) {
    bool test = true;
    if (z == 0)
	count = 0;
    else {
	test = isCircPrime((n % b) * 10 + (n / b), b, z - 1, count);
	if (!checked.test(n)) {
	    checked.set(n);
	    ++count;
	}
    }
    return sito.test(n) && test;
}

int main() {
    prosij();

    checked.reset();
    
    int count = 0, tmpcount;

#ifndef NDEBUG
    if (isCircPrime(11, 10, 2, count))
	cout << "11: " << count << endl;
    if (isCircPrime(13, 10, 2, count))
	cout << "13: " << count << endl;
    if (isCircPrime(13, 10, 2, count))
	cout << "13: " << count << endl;
    if (isCircPrime(19, 10, 2, count))
	cout << "19: " << count << endl;
#endif

#ifdef NDEBUG
    for (int b = 1, z = 1; b < maksimum ; b *= 10, ++z)
	for (int n = b; n < b * 10; ++n)
	    if (isCircPrime(n, b, z, tmpcount) && tmpcount != 0) {
		cout << n << " (" << tmpcount << ")" << endl;
		count += tmpcount;
	    }
    
    cout << "Ukupno: " << count << endl;
#endif

    return EXIT_SUCCESS;
}
