2008-02-10 22:11:31 -05:00
|
|
|
! Copyright (c) 2008 Aaron Schaefer.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2009-05-10 14:48:09 -04:00
|
|
|
USING: kernel math math.functions math.primes math.ranges
|
|
|
|
sequences project-euler.common math.bitwise ;
|
2008-02-10 22:11:31 -05:00
|
|
|
IN: project-euler.046
|
|
|
|
|
|
|
|
! http://projecteuler.net/index.php?section=problems&id=46
|
|
|
|
|
|
|
|
! DESCRIPTION
|
|
|
|
! -----------
|
|
|
|
|
|
|
|
! It was proposed by Christian Goldbach that every odd composite number can be
|
|
|
|
! written as the sum of a prime and twice a square.
|
|
|
|
|
|
|
|
! 9 = 7 + 2 * 1^2
|
|
|
|
! 15 = 7 + 2 * 2^2
|
|
|
|
! 21 = 3 + 2 * 3^2
|
|
|
|
! 25 = 7 + 2 * 3^2
|
|
|
|
! 27 = 19 + 2 * 2^2
|
|
|
|
! 33 = 31 + 2 * 1^2
|
|
|
|
|
|
|
|
! It turns out that the conjecture was false.
|
|
|
|
|
|
|
|
! What is the smallest odd composite that cannot be written as the sum of a
|
|
|
|
! prime and twice a square?
|
|
|
|
|
|
|
|
|
|
|
|
! SOLUTION
|
|
|
|
! --------
|
|
|
|
|
|
|
|
<PRIVATE
|
|
|
|
|
|
|
|
: perfect-squares ( n -- seq )
|
|
|
|
2 /i sqrt >integer [1,b] [ sq ] map ;
|
|
|
|
|
|
|
|
: fits-conjecture? ( n -- ? )
|
2009-01-29 23:19:07 -05:00
|
|
|
dup perfect-squares [ 2 * - ] with map [ prime? ] any? ;
|
2008-02-10 22:11:31 -05:00
|
|
|
|
|
|
|
: next-odd-composite ( n -- m )
|
2009-08-13 20:21:44 -04:00
|
|
|
dup odd? [ 2 + ] [ 1 + ] if dup prime? [ next-odd-composite ] when ;
|
2008-02-10 22:11:31 -05:00
|
|
|
|
|
|
|
: disprove-conjecture ( n -- m )
|
|
|
|
dup fits-conjecture? [ next-odd-composite disprove-conjecture ] when ;
|
|
|
|
|
|
|
|
PRIVATE>
|
|
|
|
|
|
|
|
: euler046 ( -- answer )
|
|
|
|
9 disprove-conjecture ;
|
|
|
|
|
|
|
|
! [ euler046 ] 100 ave-time
|
2008-11-05 01:11:15 -05:00
|
|
|
! 37 ms ave run time - 3.39 SD (100 trials)
|
2008-02-10 22:11:31 -05:00
|
|
|
|
2009-03-19 00:05:32 -04:00
|
|
|
SOLUTION: euler046
|