Project Euler Problem 35
I was apparently being OCD and put some time into the solution for Project Euler Problem 35.
Here we're trying to calculate the number of circular primes < 1,000,000. A circular prime is--well just read the problem statement.
Anyhow, here's a perl solution. It runs in about 5seconds, which isn't too bad, I guess -- could be faster.
- #!/usr/bin/perl -w
- # get all circular prime numbers < 1000000
- # circular numbers are numbers where all rotations of a prime
- # are themselves simular
- # 197 is prime. as are all rotations: 197, 971, 719.
- use strict;
- my $cache;
- # pad results. 2 is circularlly prime, but no numbers which contain it are.
- my $count = 2;
- # can filter out an numbers containing 2,4,5,6,8
- for(my $i = 1; $i < 1000000; $i++) {
- next if($i =~ m/2|4|5|6|8/);
- if(isPrime($i) && isCirc($i)) {
- $count++;
- }
- }
- sub isCirc {
- my $rotations = getRotations($x);
- foreach my $rotation (@$rotations) {
- }
- }
- sub getRotations {
- my @rotations;
- for(my $i = 0; $i < @num; $i++) {
- my $str;
- for(my $j = $i; $j < @num; $j++) {
- $str .= $num[$j];
- }
- for(my $j = 0; $j < $i; $j++) {
- $str .= $num[$j];
- }
- }
- }
- sub isPrime {
- for(my $i = 2; $i < $lim; $i++) {
- if(($x % $i) == 0) {
- $cache->{$x} = 0;
- }
- }
- $cache->{$x} = 1;
- }