Project Euler > Problem 35 > Circular primes (Java Solution)

Problem:

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?


Solution:

55


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 35
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p035 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p035().run());
 }
 
 
 private static final int LIMIT = Library.pow(10, 6);
 
 private boolean[] isPrime = Library.listPrimality(LIMIT - 1);
 
 
 public String run() {
  int count = 0;
  for (int i = 0; i < isPrime.length; i++) {
   if (isCircularPrime(i))
    count++;
  }
  return Integer.toString(count);
 }
 
 
 private boolean isCircularPrime(int n) {
  String s = Integer.toString(n);
  for (int i = 0; i < s.length(); i++) {
   if (!isPrime[Integer.parseInt(s.substring(i) + s.substring(0, i))])
    return false;
  }
  return true;
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact