Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to find the first 18 circular prime numbers (cyclically rotate left will also be prime) in Java

1 Answer

0 votes
public class MyClass {
    private static boolean is_prime(int n) {
    	if (n == 2) {
    		return true;
    	}
    	if (n < 2 || n % 2 == 0) {
    		return false;
    	}
    	for (int i = 3; i * i <= n; i += 2) {
    		if (n % i == 0) {
    			return false;
    		}
    	}
    
    	return true;
    }

    private static int cyclically_rotate_left(int n) {
    	int m = n;
    	int p = 1;
    	
    	while (m >= 10) {
    		p *= 10;
    		m /= 10;
    	}
    
    	return (int)(m + 10 * (n % p));
    }

    private static boolean is_circular_prime(int n) {
    	if (!is_prime(n)) {
    		return false;
    	}
    
    	int rotated_n = cyclically_rotate_left(n);
    	
    	while (rotated_n != n) {
    		if (rotated_n < n || !is_prime(rotated_n)) {
    			return false;
    		}
    		rotated_n = cyclically_rotate_left(rotated_n);
    	}
    	
    	return true;
    }
    
    public static void main(String args[]) {
        // 3779 = prime
	    // 7793 = prime
        // 7937 = prime
	    // 9377 = prime

	    int n = 2;

    	for (int i = 0; i < 18; n++) {
    		if (is_circular_prime(n)) {
    			if (i > 0) {
    				System.out.print(", ");
    			}
    			System.out.print(n);
    			i++;
    		}
    	}
    }
}






/*
run:

2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939

*/

 



answered Mar 23, 2023 by avibootz
...