Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package circularPrimes;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class CircularPrimes {
- public static void main(String[] args) {
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- System.out.println("Input number to count circ primes up to: ");
- int n = 0;
- try {
- n = Integer.parseInt(in.readLine());
- } catch (NumberFormatException e1) {
- System.out.println("Please enter a valid number");
- return;
- } catch (IOException e1) {
- System.out.println("Unnamed exception occurred.");
- e1.printStackTrace();
- }
- int count = 0;
- for (int i = 2; i < n; i++) {
- if (isCircPrime(i)) {
- count++;
- System.out.println(i);
- }
- }
- System.out.println("There are " + Integer.toString(count) + " circular primes below " + n);
- }
- public static char[] rotateDigits(char[] xArr) {
- char[] rotatedArr = new char[xArr.length];
- rotatedArr[rotatedArr.length - 1] = xArr[0];
- for (int i = 0; i <= xArr.length - 2; i++) {
- rotatedArr[i] = xArr[i + 1];
- }
- return rotatedArr;
- }
- public static boolean isCircPrime(int x) {
- if (isPrime(x)) {
- // First rotation of digits is prime
- // Continue checking
- char[] currentRotation = rotateDigits(Integer.toString(x).toCharArray());
- for (int i = 0; i < currentRotation.length - 1; i++) {
- // Rotate so that each digit rotation is cycled through and checked
- String currentRotationString = new String(currentRotation);
- if (!isPrime(Integer.parseInt(currentRotationString))) {
- // A rotation is not prime
- return false;
- }
- currentRotation = rotateDigits(currentRotation);
- }
- return true;
- } else {
- return false;
- }
- }
- public static boolean isPrime(int x) {
- if (x == 1 || x == 2) {
- return true;
- }
- else if (x % 2 == 0 || x % 5 == 0) {
- return false;
- }
- else {
- for (int i = 3; i < Math.floor(Math.sqrt(x)); i += 2) {
- if (x % i == 0) {
- return false;
- }
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment