/extra/project-euler/052/052.factor

http://github.com/abeaumont/factor · Factor · 51 lines · 21 code · 16 blank · 14 comment · 5 complexity · 3f5e4a84c350739d4bc9cd5c1206d6e2 MD5 · raw file

  1. ! Copyright (c) 2008 Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: combinators.short-circuit kernel math math.functions
  4. project-euler.common sequences sorting grouping ;
  5. IN: project-euler.052
  6. ! http://projecteuler.net/index.php?section=problems&id=52
  7. ! DESCRIPTION
  8. ! -----------
  9. ! It can be seen that the number, 125874, and its double, 251748, contain
  10. ! exactly the same digits, but in a different order.
  11. ! Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x,
  12. ! contain the same digits.
  13. ! SOLUTION
  14. ! --------
  15. ! Analysis shows the number must be odd, divisible by 3, and larger than 123456
  16. <PRIVATE
  17. : map-nx ( n x -- seq )
  18. iota [ 1 + * ] with map ; inline
  19. : all-same-digits? ( seq -- ? )
  20. [ number>digits natural-sort ] map all-equal? ;
  21. : candidate? ( n -- ? )
  22. { [ odd? ] [ 3 divisor? ] } 1&& ;
  23. : next-all-same ( x n -- n )
  24. dup candidate? [
  25. 2dup swap map-nx all-same-digits?
  26. [ nip ] [ 1 + next-all-same ] if
  27. ] [
  28. 1 + next-all-same
  29. ] if ;
  30. PRIVATE>
  31. : euler052 ( -- answer )
  32. 6 123456 next-all-same ;
  33. ! [ euler052 ] 100 ave-time
  34. ! 92 ms ave run time - 6.29 SD (100 trials)
  35. SOLUTION: euler052