Find all circular primes less than given number n. A prime number is a Circular Prime Number if all of its possible rotations are itself prime numbers.
Examples :
79 is a circular prime.
as 79 and 97 are prime numbers.
But 23 is not a circular prime.
as 23 is prime but 32 is not a prime number.
Algorithm:
-> Find prime numbers up to n using Sieve of Sundaram algorithm.
-> Now for every prime number from sieve method,
one after another, we should check whether its all
rotations are prime or not:
-> If yes then print that prime number.
-> If no then skip that prime number.
Below is the implementation of the above algorithm :
C++
// C++ program to print primes smaller than n using // Sieve of Sundaram. #include <bits/stdc++.h> using namespace std;
// Prototypes of the methods used void SieveOfSundaram( bool marked[], int );
int Rotate( int );
int countDigits( int );
// Print all circular primes void circularPrime( int n)
{ // In general Sieve of Sundaram, produces primes smaller
// than (2*x + 2) for a number given number x.
// Since we want primes smaller than n, we reduce n to half
int nNew = (n - 2) / 2;
// This array is used to separate numbers of the form i+j+2ij
// from others where 1 <= i <= j
bool marked[nNew + 1];
// Initialize all elements as not marked
memset (marked, false , sizeof (marked));
SieveOfSundaram(marked, nNew);
// if n > 2 then 2 is also a circular prime
cout << "2 " ;
// According to Sieve of sundaram If marked[i] is false
// then 2*i + 1 is a prime number.
// loop to check all prime numbers and their rotations
for ( int i = 1; i <= nNew; i++) {
// Skip this number if not prime
if (marked[i] == true )
continue ;
int num = 2 * i + 1;
num = Rotate(num); // function for rotation of prime
// now we check for rotations of this prime number
// if new rotation is prime check next rotation,
// till new rotation becomes the actual prime number
// and if new rotation if not prime then break
while (num != 2 * i + 1) {
if (num % 2 == 0) // check for even
break ;
// if rotated number is prime then rotate
// for next
if (marked[(num - 1) / 2] == false )
num = Rotate(num);
else
break ;
}
// if checked number is circular prime print it
if (num == (2 * i + 1))
cout << num << " " ;
}
} // Sieve of Sundaram for generating prime number void SieveOfSundaram( bool marked[], int nNew)
{ // Main logic of Sundaram. Mark all numbers of the
// form i + j + 2ij as true where 1 <= i <= j
for ( int i = 1; i <= nNew; i++)
for ( int j = i; (i + j + 2 * i * j) <= nNew; j++)
marked[i + j + 2 * i * j] = true ;
} // Rotate function to right rotate the number int Rotate( int n)
{ int rem = n % 10; // find unit place number
rem *= pow (10, countDigits(n)); // to put unit place
// number as first digit.
n /= 10; // remove unit digit
n += rem; // add first digit to rest
return n;
} // Function to find total number of digits int countDigits( int n)
{ int digit = 0;
while (n /= 10)
digit++;
return digit;
} // Driver program to test above int main( void )
{ int n = 100;
circularPrime(n);
return 0;
} |
Java
// Java program to print primes smaller // than n using Sieve of Sundaram. import java.util.Arrays;
class GFG {
// Print all circular primes
static void circularPrime( int n)
{
// In general Sieve of Sundaram, produces
// primes smaller than (2*x + 2) for a
// number given number x.Since we want
// primes smaller than n, we reduce n to half
int nNew = (n - 2 ) / 2 ;
// This array is used to separate numbers of the
// form i+j+2ij from others where 1 <= i <= j
boolean marked[] = new boolean [nNew + 1 ];
// Initialize all elements as not marked
Arrays.fill(marked, false );
SieveOfSundaram(marked, nNew);
// if n > 2 then 2 is also a circular prime
System.out.print( "2 " );
// According to Sieve of sundaram If marked[i] is false
// then 2*i + 1 is a prime number.
// loop to check all prime numbers and their rotations
for ( int i = 1 ; i <= nNew; i++) {
// Skip this number if not prime
if (marked[i] == true )
continue ;
int num = 2 * i + 1 ;
num = Rotate(num); // function for rotation of prime
// now we check for rotations of this prime number
// if new rotation is prime check next rotation,
// till new rotation becomes the actual prime number
// and if new rotation if not prime then break
while (num != 2 * i + 1 ) {
if (num % 2 == 0 ) // check for even
break ;
// if rotated number is prime then rotate
// for next
if (marked[(num - 1 ) / 2 ] == false )
num = Rotate(num);
else
break ;
}
// if checked number is circular prime print it
if (num == ( 2 * i + 1 ))
System.out.print(num + " " );
}
}
// Sieve of Sundaram for generating prime number
static void SieveOfSundaram( boolean marked[], int nNew)
{
// Main logic of Sundaram. Mark all numbers of the
// form i + j + 2ij as true where 1 <= i <= j
for ( int i = 1 ; i <= nNew; i++)
for ( int j = i; (i + j + 2 * i * j) <= nNew; j++)
marked[i + j + 2 * i * j] = true ;
}
// Function to find total number of digits
static int countDigits( int n)
{
int digit = 0 ;
while ((n /= 10 ) > 0 )
digit++;
return digit;
}
// Rotate function to right rotate the number
static int Rotate( int n)
{
int rem = n % 10 ; // find unit place number
rem *= Math.pow( 10 , countDigits(n)); // to put unit place
// number as first digit.
n /= 10 ; // remove unit digit
n += rem; // add first digit to rest
return n;
}
// Driver code
public static void main(String[] args)
{
int n = 100 ;
circularPrime(n);
}
} // This code is contributed by Anant Agarwal. |
Python3
# Python3 program to print primes smaller # than n using Sieve of Sundaram. # Print all circular primes def circularPrime(n):
# In general Sieve of Sundaram,
# produces primes smaller than
# (2*x + 2) for a number given
# number x. Since we want primes
# smaller than n, we reduce n to half
nNew = (n - 2 ) / / 2
# This array is used to separate numbers
# of the form i+j+2ij from others
# where 1 <= i <= j
marked = [ False for i in range (nNew + 1 )]
SieveOfSundaram(marked, nNew)
# If n > 2 then 2 is also a
# circular prime
print ( "2" , end = ' ' )
# According to Sieve of sundaram
# If marked[i] is false then
# 2*i + 1 is a prime number.
# Loop to check all prime numbers
# and their rotations
for i in range ( 1 , nNew + 1 ):
# Skip this number if not prime
if (marked[i] = = True ):
continue ;
num = 2 * i + 1
# Function for rotation of prime
num = Rotate(num)
# Now we check for rotations of this
# prime number if new rotation is
# prime check next rotation, till
# new rotation becomes the actual
# prime number and if new rotation
# if not prime then break
while (num ! = 2 * i + 1 ):
# Check for even
if (num % 2 = = 0 ):
break
# If rotated number is prime
# then rotate for next
if (marked[(num - 1 ) / / 2 ] = = False ):
num = Rotate(num);
else :
break ;
# If checked number is circular
# prime print it
if (num = = ( 2 * i + 1 )):
print (num, end = ' ' )
# Sieve of Sundaram for generating # prime number def SieveOfSundaram(marked, nNew):
# Main logic of Sundaram. Mark
# all numbers of the form
# i + j + 2ij as true where 1 <= i <= j
for i in range ( 1 , nNew + 1 ):
j = i
while (i + j + 2 * i * j) < = nNew:
marked[i + j + 2 * i * j] = True
j + = 1
# Rotate function to right rotate # the number def Rotate(n):
# Find unit place number
rem = n % 10
# To put unit place
rem = rem * ( 10 * * (countDigits(n) - 1 ))
# Number as first digit.
n = n / / 10 # Remove unit digit
n + = rem # Add first digit to rest
return n
# Function to find total number of digits def countDigits(n):
digit = 0
while n ! = 0 :
n = n / / 10
digit + = 1
return digit
# Driver code if __name__ = = "__main__" :
n = 100
circularPrime(n)
# This code is contributed by rutvik_56 |
C#
// C# program to print primes smaller // than n using Sieve of Sundaram. using System;
class GFG {
// Print all circular primes
static void circularPrime( int n)
{
// In general Sieve of Sundaram, produces
// primes smaller than (2*x + 2) for a
// number given number x.Since we want
// primes smaller than n, we reduce n to half
int nNew = (n - 2) / 2;
// This array is used to separate numbers of the
// form i+j+2ij from others where 1 <= i <= j
bool [] marked = new bool [nNew + 1];
// Initialize all elements as not marked
// Arrays.fill(marked, false);
SieveOfSundaram(marked, nNew);
// if n > 2 then 2 is also a circular prime
Console.Write( "2 " );
// According to Sieve of sundaram If
// marked[i] is false then 2*i + 1 is a
// prime number.
// loop to check all prime numbers
// and their rotations
for ( int i = 1; i <= nNew; i++) {
// Skip this number if not prime
if (marked[i] == true )
continue ;
int num = 2 * i + 1;
// function for rotation of prime
num = Rotate(num);
// now we check for rotations of this prime number
// if new rotation is prime check next rotation,
// till new rotation becomes the actual prime number
// and if new rotation if not prime then break
while (num != 2 * i + 1) {
if (num % 2 == 0) // check for even
break ;
// if rotated number is prime
// then rotate for next
if (marked[(num - 1) / 2] == false )
num = Rotate(num);
else
break ;
}
// if checked number is circular prime print it
if (num == (2 * i + 1))
Console.Write(num + " " );
}
}
// Sieve of Sundaram for generating prime number
static void SieveOfSundaram( bool [] marked, int nNew)
{
// Main logic of Sundaram. Mark all numbers of the
// form i + j + 2ij as true where 1 <= i <= j
for ( int i = 1; i <= nNew; i++)
for ( int j = i; (i + j + 2 * i * j) <= nNew; j++)
marked[i + j + 2 * i * j] = true ;
}
// Function to find total number of digits
static int countDigits( int n)
{
int digit = 0;
while ((n /= 10) > 0)
digit++;
return digit;
}
// Rotate function to right rotate the number
static int Rotate( int n)
{
// find unit place number
int rem = n % 10;
// to put unit place
rem *= ( int )Math.Pow(10, countDigits(n));
// number as first digit.
n /= 10; // remove unit digit
n += rem; // add first digit to rest
return n;
}
// Driver code
public static void Main()
{
int n = 100;
circularPrime(n);
}
} // This code is contributed by vt_m. |
Javascript
<script> // Javascript program to print // primes smaller // than n using Sieve of Sundaram. // Print all circular primes function circularPrime(n)
{ // In general Sieve of Sundaram, produces
// primes smaller than (2*x + 2) for a
// number given number x.Since we want
// primes smaller than n, we reduce n to half
var nNew = (n - 2) / 2;
// This array is used to
// separate numbers of the
// form i+j+2ij from others
// where 1 <= i <= j
marked = Array.from({length: nNew + 1},
(_, i) => false );
SieveOfSundaram(marked, nNew);
// if n > 2 then 2 is also a circular prime
document.write( "2 " );
// According to Sieve of sundaram
// If marked[i] is false
// then 2*i + 1 is a prime number.
// loop to check all prime numbers
// and their rotations
for (i = 1; i <= nNew; i++) {
// Skip this number if not prime
if (marked[i] == true )
continue ;
var num = 2 * i + 1;
// function for rotation of prime
num = Rotate(num);
// now we check for rotations of
// this prime number
// if new rotation is prime check
// next rotation,
// till new rotation becomes
// the actual prime number
// and if new rotation if
// not prime then break
while (num != 2 * i + 1) {
if (num % 2 == 0) // check for even
break ;
// if rotated number is prime then rotate
// for next
if (marked[parseInt((num - 1) / 2)] == false )
num = Rotate(num);
else
break ;
}
// if checked number is circular prime print it
if (num == (2 * i + 1))
document.write(num + " " );
}
} // Sieve of Sundaram for generating prime number function SieveOfSundaram(marked , nNew)
{ // Main logic of Sundaram. Mark all numbers of the
// form i + j + 2ij as true where 1 <= i <= j for (i = 1; i <= nNew; i++)
for (j = i; (i + j + 2 * i * j) <= nNew; j++)
marked[i + j + 2 * i * j] = true ;
} // Function to find total number of digits function countDigits(n)
{ var digit = 0;
while ((n = parseInt(n/10)) > 0)
digit++;
return digit;
} // Rotate function to right rotate the number function Rotate(n)
{ // find unit place number
var rem = n % 10;
// to put unit place
rem *= Math.pow(10, countDigits(n));
// number as first digit.
n = parseInt(n/10) // remove unit digit
n += rem; // add first digit to rest
return n;
} // Driver code var n = 100;
circularPrime(n); // This code is contributed by Amit Katiyar </script> |
PHP
<?php // PHP program to print primes smaller than // n using Sieve of Sundaram. // Print all circular primes function circularPrime( $n )
{ // In general Sieve of Sundaram, produces
// primes smaller than (2*x + 2) for a number
// given number x. Since we want primes smaller
// than n, we reduce n to half
$nNew = (int)(( $n - 2) / 2);
// This array is used to separate numbers of
// the form i+j+2ij from others where 1 <= i <= j
$marked = array_fill (0, $nNew + 1, false);
SieveOfSundaram( $marked , $nNew );
// if n > 2 then 2 is also a circular prime
print ( "2 " );
// According to Sieve of sundaram If marked[i]
// is false then 2*i + 1 is a prime number.
// loop to check all prime numbers
// and their rotations
for ( $i = 1; $i <= $nNew ; $i ++)
{
// Skip this number if not prime
if ( $marked [ $i ] == true)
continue ;
$num = 2 * $i + 1;
$num = Rotate( $num ); // function for rotation of prime
// now we check for rotations of this
// prime number if new rotation is prime
// check next rotation, till new rotation
// becomes the actual prime number and if
// new rotation if not prime then break
while ( $num != 2 * $i + 1)
{
if ( $num % 2 == 0) // check for even
break ;
// if rotated number is prime then
// rotate for next
if ( $marked [(int)(( $num - 1) / 2)] == false)
$num = Rotate( $num );
else
break ;
}
// if checked number is circular
// prime print it
if ( $num == (2 * $i + 1))
print ( $num . " " );
}
} // Sieve of Sundaram for generating prime number function SieveOfSundaram(& $marked , $nNew )
{ // Main logic of Sundaram. Mark all numbers of the
// form i + j + 2ij as true where 1 <= i <= j
for ( $i = 1; $i <= $nNew ; $i ++)
for ( $j = $i ;
( $i + $j + 2 * $i * $j ) <= $nNew ; $j ++)
$marked [ $i + $j + 2 * $i * $j ] = true;
} // Rotate function to right rotate the number function Rotate( $n )
{ $rem = $n % 10; // find unit place number
$rem *= pow(10, countDigits( $n )); // to put unit place
// number as first digit.
$n = (int)( $n / 10); // remove unit digit
$n += $rem ; // add first digit to rest
return $n ;
} // Function to find total number of digits function countDigits( $n )
{ $digit = 0;
$n = (int)( $n / 10);
while ( $n )
{
$digit ++;
$n = (int)( $n / 10);
}
return $digit ;
} // Driver Code $n = 100;
circularPrime( $n );
// This code is contributed by mits ?> |
Output:
2 3 5 7 11 13 17 31 37 71 73 79 97
Approach 2:
Step-by-step approach:
- Generate all primes up to n using the Sieve of Eratosthenes algorithm.
- For each prime p, check if it is a circular prime by rotating its digits and checking if the resulting numbers are also prime.
- If all rotations of p are prime, then p is a circular prime.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h> using namespace std;
// Generate all primes up toA n using the Sieve of Eratosthenes algorithm void generatePrimes( int n, vector< int >& primes) {
vector< bool > isPrime(n+1, true );
isPrime[0] = isPrime[1] = false ;
for ( int i = 2; i <= sqrt (n); i++) {
if (isPrime[i]) {
for ( int j = i*i; j <= n; j += i) {
isPrime[j] = false ;
}
}
}
for ( int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.push_back(i);
}
}
} // Check if a number is a circular prime bool isCircularPrime( int n, const vector< int >& primes) {
string num = to_string(n);
for ( int i = 0; i < num.size(); i++) {
rotate(num.begin(), num.begin()+1, num.end()); // rotate the digits
int rotatedNum = stoi(num);
if (!binary_search(primes.begin(), primes.end(), rotatedNum)) {
return false ;
}
}
return true ;
} // Find all circular primes up to n void circularPrimes( int n) {
vector< int > primes;
generatePrimes(n, primes);
for ( int i = 0; i < primes.size(); i++) {
if (isCircularPrime(primes[i], primes)) {
cout << primes[i] << " " ;
}
}
} // Driver program to test above int main( void ) {
int n = 100;
circularPrimes(n);
return 0;
} |
Java
import java.util.ArrayList;
import java.util.List;
public class CircularPrimes {
// Generate all primes up to n using the Sieve of Eratosthenes algorithm
static void generatePrimes( int n, List<Integer> primes) {
boolean [] isPrime = new boolean [n + 1 ];
for ( int i = 0 ; i <= n; i++) {
isPrime[i] = true ;
}
isPrime[ 0 ] = isPrime[ 1 ] = false ;
for ( int i = 2 ; i <= Math.sqrt(n); i++) {
if (isPrime[i]) {
for ( int j = i * i; j <= n; j += i) {
isPrime[j] = false ;
}
}
}
for ( int i = 2 ; i <= n; i++) {
if (isPrime[i]) {
primes.add(i);
}
}
}
// Check if a number is a circular prime
static boolean isCircularPrime( int n, List<Integer> primes) {
String num = Integer.toString(n);
for ( int i = 0 ; i < num.length(); i++) {
num = num.substring( 1 ) + num.charAt( 0 ); // rotate the digits
int rotatedNum = Integer.parseInt(num);
if (!primes.contains(rotatedNum)) {
return false ;
}
}
return true ;
}
// Find all circular primes up to n
static void circularPrimes( int n) {
List<Integer> primes = new ArrayList<>();
generatePrimes(n, primes);
for ( int prime : primes) {
if (isCircularPrime(prime, primes)) {
System.out.print(prime + " " );
}
}
}
// Driver program to test above
public static void main(String[] args) {
int n = 100 ;
circularPrimes(n);
}
} |
Python3
import math
# Generate all primes up to n using the Sieve of Eratosthenes algorithm def generate_primes(n):
is_prime = [ True ] * (n + 1 )
is_prime[ 0 ] = is_prime[ 1 ] = False
for i in range ( 2 , int (math.sqrt(n)) + 1 ):
if is_prime[i]:
for j in range (i * i, n + 1 , i):
is_prime[j] = False
primes = []
for i in range ( 2 , n + 1 ):
if is_prime[i]:
primes.append(i)
return primes
# Check if a number is a circular prime def is_circular_prime(n, primes):
num = str (n)
for i in range ( len (num)):
num = num[ 1 :] + num[ 0 ] # rotate the digits
rotated_num = int (num)
if rotated_num not in primes:
return False
return True
# Find all circular primes up to n def circular_primes(n):
primes = generate_primes(n)
for p in primes:
if is_circular_prime(p, primes):
print (p, end = " " )
# Driver program to test above if __name__ = = '__main__' :
n = 100
circular_primes(n)
|
C#
using System;
using System.Collections.Generic;
class Program
{ // Generate all primes up to n using the Sieve of Eratosthenes algorithm
static List< int > GeneratePrimes( int n)
{
bool [] isPrime = new bool [n + 1];
for ( int i = 0; i <= n; i++)
{
isPrime[i] = true ;
}
isPrime[0] = isPrime[1] = false ;
for ( int i = 2; i <= Math.Sqrt(n); i++)
{
if (isPrime[i])
{
for ( int j = i * i; j <= n; j += i)
{
isPrime[j] = false ;
}
}
}
List< int > primes = new List< int >();
for ( int i = 2; i <= n; i++)
{
if (isPrime[i])
{
primes.Add(i);
}
}
return primes;
}
// Check if a number is a circular prime
static bool IsCircularPrime( int n, List< int > primes)
{
string num = n.ToString();
for ( int i = 0; i < num.Length; i++)
{
num = num.Substring(1) + num[0].ToString(); // rotate the digits
int rotatedNum = int .Parse(num);
if (!primes.Contains(rotatedNum))
{
return false ;
}
}
return true ;
}
// Find all circular primes up to n
static void CircularPrimes( int n)
{
List< int > primes = GeneratePrimes(n);
foreach ( int p in primes)
{
if (IsCircularPrime(p, primes))
{
Console.Write(p + " " );
}
}
}
// Driver program to test above
static void Main()
{
int n = 100;
CircularPrimes(n);
}
} |
Javascript
// Function to generate all primes up to 'n' using the Sieve of Eratosthenes algorithm function generatePrimes(n) {
const isPrime = new Array(n + 1).fill( true );
isPrime[0] = isPrime[1] = false ;
// Mark non-prime numbers
for (let i = 2; i <= Math.sqrt(n); i++) {
if (isPrime[i]) {
for (let j = i * i; j <= n; j += i) {
isPrime[j] = false ;
}
}
}
const primes = [];
for (let i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.push(i);
}
}
return primes;
} // Function to check if a number is a circular prime function isCircularPrime(n, primes) {
let numStr = n.toString();
// Check all rotations of the number
for (let i = 0; i < numStr.length; i++) {
numStr = numStr.substring(1) + numStr.charAt(0); // Rotate the digits
const rotatedNum = parseInt(numStr);
if (!primes.includes(rotatedNum)) {
return false ;
}
}
return true ;
} // Function to find and display all circular prime numbers up to 'n' function circularPrimes(n) {
const primes = generatePrimes(n);
for (const prime of primes) {
if (isCircularPrime(prime, primes)) {
console.log(prime + ' ' ); // Print circular primes
}
}
console.log(); // Newline for better formatting
} const n = 100; // Set the limit for finding circular primes
circularPrimes(n); |
Output
2 3 5 7 11 13 17 31 37 71 73 79 97
Time Complexity: O(n log log n), where n is the input number. This is because the Sieve of Sundaram algorithm used.
Auxiliary Space: O(n log log n).