Skip to content

Instantly share code, notes, and snippets.

@jbnv
Created September 13, 2016 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbnv/c80abc774e8f147f367da29e8e5ef3cb to your computer and use it in GitHub Desktop.
Save jbnv/c80abc774e8f147f367da29e8e5ef3cb to your computer and use it in GitHub Desktop.
Function to determine number of circular primes in a range.
/*
A number is called a circular prime if it is prime and all of its rotations are primes.
For example, the number 197 has two rotations: 971, and 719. Both of them are prime.
Another example: 1193 is a circular prime, since 1931, 9311 and 3119 all are also prime.
*/
function isPrime(n) {
if (n == 1) return false;
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
function rotate(n) {
var nn = ""+n;
var n2 = nn[nn.length-1]+nn.substring(0,nn.length-1);
return parseInt(n2);
}
function circular(N) {
var outbound = 0;
for (var i = 2; i <= N; i++) {
var isMatch = true;
var check = i;
for (j = 0; j < (""+i).length; ++j) {
if (!isPrime(check)) {
isMatch = false;
break;
}
check = rotate(check);
}
if (isMatch) outbound++;
}
return outbound;
}
console.log(circular(1));
console.log(circular(100));
console.log(circular(10000));
console.log(circular(1000000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment