/extra/project-euler/033/033.factor

http://github.com/abeaumont/factor · Factor · 55 lines · 17 code · 19 blank · 19 comment · 6 complexity · 46a536692eacce964cffd9d1c7c8fc83 MD5 · raw file

  1. ! Copyright (c) 2008 Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: kernel math math.ranges project-euler.common sequences ;
  4. IN: project-euler.033
  5. ! http://projecteuler.net/index.php?section=problems&id=33
  6. ! DESCRIPTION
  7. ! -----------
  8. ! The fraction 49/98 is a curious fraction, as an inexperienced mathematician
  9. ! in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which
  10. ! is correct, is obtained by cancelling the 9s.
  11. ! We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
  12. ! There are exactly four non-trivial examples of this type of fraction, less
  13. ! than one in value, and containing two digits in the numerator and
  14. ! denominator.
  15. ! If the product of these four fractions is given in its lowest common terms,
  16. ! find the value of the denominator.
  17. ! SOLUTION
  18. ! --------
  19. ! Through analysis, you only need to check fractions fitting the pattern ax/xb
  20. <PRIVATE
  21. : source-033 ( -- seq )
  22. 10 99 [a,b] dup cartesian-product concat [ first2 < ] filter ;
  23. : safe? ( ax xb -- ? )
  24. [ 10 /mod ] bi@ [ = ] dip zero? not and nip ;
  25. : ax/xb ( ax xb -- z/f )
  26. 2dup safe? [ [ 10 /mod ] bi@ 2nip / ] [ 2drop f ] if ;
  27. : curious? ( m n -- ? )
  28. 2dup / [ ax/xb ] dip = ;
  29. : curious-fractions ( seq -- seq )
  30. [ first2 curious? ] filter [ first2 / ] map ;
  31. PRIVATE>
  32. : euler033 ( -- answer )
  33. source-033 curious-fractions product denominator ;
  34. ! [ euler033 ] 100 ave-time
  35. ! 7 ms ave run time - 1.31 SD (100 trials)
  36. SOLUTION: euler033