Zachary Stence

Problem 35: Circular primes

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?

[?1049h[?1h=[?12;25h[?12l[?25h[?25l~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ 0,0-1AllVIM - Vi IMprovedversion 7.4.1099by Bram Moolenaar et al.Modified by Vim is open source and freely distributableBecome a registered Vim user!type :help register for information type :q to exit type :help or  for on-line helptype :help version7 for version info[?12l[?25h[?25lType :quit to exit Vim0,0-1All[?12l[?25h[?25l0,0-1All[?12l[?25h[?25l0,0-1All[?12l[?25h[?25l0,0-1All[?12l[?25h[?1l>[?1049lVim: Error reading input, exiting... Vim: Finished. 
#include <iostream> 
#include <math.h>
#include <string>
using namespace std;

const int UPPER = 1000000;

int power(int b, int x) {
  int result = 1;
  for (int i = 0; i < x; i++) {
    result *= b;
  }
  return result;
}

int rotate(int x) {
  int digits = floor(log10(x)+1);
  int n = power(10, digits-1);
  return (x % n)*10 + floor(x/n);
}

bool isPrime(int x) {
  if (x == 1) return false;
  for (int i = 2; i <= floor(sqrt(x)); i++) {
    if (x % i == 0) return false;
  }
  return true;
}

bool doesContain(int num, int d) {
  int digits = floor(log10(num)+1);
  for (int i = digits; i > 0; i--) {
    if (num % 10 == d)
      return true;
    else
      num /= 10;
  }
  return false;
}


bool isCircular(int x) {
  if (doesContain(x, 0)) return false;
  int rot = floor(log10(x));
  for (int i = 0; i <= rot; i++) {
    if (!isPrime(x)) {
      return false;
    }
  x = rotate(x);
  }
  return true;
}

int main() {
  int count = 0;
  for (int i = 1; i < UPPER; i++) {
   if(isCircular(i)==true) {
      count++;
    }
  }
  cout << count << endl;
}

Answer: 55