]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/040/040.factor
project-euler: Rewrap, update links, add copyrights, tests
[factor.git] / extra / project-euler / 040 / 040.factor
1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.parser sequences project-euler.common ;
4 IN: project-euler.040
5
6 ! https://projecteuler.net/problem=40
7
8 ! DESCRIPTION
9 ! -----------
10
11 ! An irrational decimal fraction is created by concatenating the
12 ! positive integers:
13
14 !     0.123456789101112131415161718192021...
15
16 ! It can be seen that the 12th digit of the fractional part is
17 ! 1.
18
19 ! If dn represents the nth digit of the fractional part, find
20 ! the value of the following expression.
21
22 !     d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
23
24
25 ! SOLUTION
26 ! --------
27
28 <PRIVATE
29
30 : (concat-upto) ( n limit str -- str )
31     2dup length > [
32         pick number>string append! [ 1 + ] 2dip (concat-upto)
33     ] [
34         2nip
35     ] if ;
36
37 : concat-upto ( n -- str )
38     SBUF" " clone 1 -rot (concat-upto) ;
39
40 : nth-integer ( n str -- m )
41     [ 1 - ] dip nth digit> ;
42
43 PRIVATE>
44
45 : euler040 ( -- answer )
46     1000000 concat-upto { 1 10 100 1000 10000 100000 1000000 }
47     [ swap nth-integer ] with map product ;
48
49 ! [ euler040 ] 100 ave-time
50 ! 444 ms ave run time - 23.64 SD (100 trials)
51
52 SOLUTION: euler040