factor/extra/project-euler/028/028.factor

47 lines
1.0 KiB
Factor
Raw Normal View History

! Copyright (c) 2008 Aaron Schaefer.
2008-01-17 23:37:10 -05:00
! See http://factorcode.org/license.txt for BSD license.
USING: kernel math math.ranges sequences project-euler.common ;
2008-01-17 23:37:10 -05:00
IN: project-euler.028
! http://projecteuler.net/index.php?section=problems&id=28
! DESCRIPTION
! -----------
! Starting with the number 1 and moving to the right in a clockwise direction a
! 5 by 5 spiral is formed as follows:
! 21 22 23 24 25
! 20 7 8 9 10
! 19 6 1 2 11
! 18 5 4 3 12
! 17 16 15 14 13
! It can be verified that the sum of both diagonals is 101.
! What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?
! SOLUTION
! --------
! For a square sized n by n, the sum of corners is 4n² - 6n + 6
2008-01-17 23:37:10 -05:00
<PRIVATE
: sum-corners ( n -- sum )
2008-10-30 22:04:44 -04:00
dup 1 = [ [ sq 4 * ] [ 6 * ] bi - 6 + ] unless ;
2008-01-17 23:37:10 -05:00
: sum-diags ( n -- sum )
2009-10-29 15:34:04 -04:00
1 swap 2 <range> [ sum-corners ] map-sum ;
2008-01-17 23:37:10 -05:00
PRIVATE>
: euler028 ( -- answer )
1001 sum-diags ;
2008-01-17 23:37:10 -05:00
2008-01-18 01:24:55 -05:00
! [ euler028 ] 100 ave-time
2008-10-30 22:04:44 -04:00
! 0 ms ave run time - 0.39 SD (100 trials)
2008-01-17 23:37:10 -05:00
SOLUTION: euler028