I need help with my algorithm for finding circular primes. If you don't know what a circular prime is, it's when a number, say 179, and its rotations, 179, 917, and 791, are all prime. The algorithm simply checks if the number is a circular prime. The problem I'm using it for is finding the sum of all circular primes under 1,000,000. It's fast enough up until around 100,000, around 6 seconds. What can be done to speed it up?

/** * @param num * @return true if the number is a circular prime * @return false if the number is not a circular prime */ public static boolean isCircularPrime(long num) { String number = Long.toString(num);//string containing the number if(!isPrime(num))//false if the number isn't prime { return false; } else//checks other possibilities { if(num>=10)//numbers with two or more digits can only be a circular prime if they are made of 1, 3, 7, or 9 { if(number.contains("2")||number.contains("4")||number.contains("6")||number.contains("8")||number.contains("5")||number.contains("0"))//false if it contains a positive number, five, or zero { return false; } else//checks more if it doesn't contain an "illegal" number { for(int i = 0; i < number.length(); i++)//loops it for the length of the number { num = rotate(num);//rotates the number once if(!isPrime(num))//false if the rotation isn't prime return false; } return true;//true if it the number and all rotations are prime } } else { return true; } } } //rotates the number once public static int rotate(long number) { long start = number; int numdigits = (int) Math.log10((double)number); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); int num = 0; long q = number / 10; long r = number % 10; //1234 = 123; number = number / 10; number = number + multiplier * r; num = (int) number; return num; }

Sieve of Eratosthenes to get a list of the primes.

//shows all prime numbers to a specified max public static int[] primesUpTo(int s) { // initially assume all integers are prime boolean[] isPrime = new boolean[s + 1]; for (int i = 2; i <= s; i++) { isPrime[i] = true; } // mark non-primes <= N using Sieve of Eratosthenes for (int i = 2; i*i <= s; i++) { // if i is prime, then mark multiples of i as nonprime // suffices to consider mutiples i, i+1, ..., N/i if (isPrime[i]) { for (int j = i; i*j <= s; j++) { isPrime[i*j] = false; } } } int primes = 0; for (int i = 2; i <= s; i++) { if (isPrime[i]) { primes++; } } int[] nums = new int[primes]; int index = 0; for(int i = 2; i <= s; i++) { if (isPrime[i]) { nums[index] = i; index++; } } return nums; }

I get the prime list fast enough, 32 ms. for 1,000,000.