/extra/project-euler/035/035.factor

http://github.com/abeaumont/factor · Factor · 61 lines · 27 code · 18 blank · 16 comment · 6 complexity · 2286f1fa5ac45df1ff88396f7b59b906 MD5 · raw file

  1. ! Copyright (c) 2008 Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: kernel math math.combinatorics math.parser math.primes
  4. project-euler.common sequences ;
  5. IN: project-euler.035
  6. ! http://projecteuler.net/index.php?section=problems&id=35
  7. ! DESCRIPTION
  8. ! -----------
  9. ! The number, 197, is called a circular prime because all rotations of the
  10. ! digits: 197, 971, and 719, are themselves prime.
  11. ! There are thirteen such primes below 100:
  12. ! 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
  13. ! How many circular primes are there below one million?
  14. ! SOLUTION
  15. ! --------
  16. <PRIVATE
  17. : source-035 ( -- seq )
  18. 1000000 primes-upto [ number>digits ] map ;
  19. : possible? ( seq -- ? )
  20. dup length 1 > [
  21. [ even? ] any? not
  22. ] [
  23. drop t
  24. ] if ;
  25. : rotate ( seq n -- seq )
  26. cut* prepend ;
  27. : (circular?) ( seq n -- ? )
  28. dup 0 > [
  29. 2dup rotate 10 digits>integer
  30. prime? [ 1 - (circular?) ] [ 2drop f ] if
  31. ] [
  32. 2drop t
  33. ] if ;
  34. : circular? ( seq -- ? )
  35. dup length 1 - (circular?) ;
  36. PRIVATE>
  37. : euler035 ( -- answer )
  38. source-035 [ possible? ] filter [ circular? ] count ;
  39. ! [ euler035 ] 100 ave-time
  40. ! 538 ms ave run time - 17.16 SD (100 trials)
  41. ! TODO: try using bit arrays or other methods outlined here:
  42. ! http://home.comcast.net/~babdulbaki/Circular_Primes.html
  43. SOLUTION: euler035