]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/175/175.factor
Delete empty unit tests files, remove 1- and 1+, reorder IN: lines in a lot of places...
[factor.git] / extra / project-euler / 175 / 175.factor
1 ! Copyright (c) 2007 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators kernel math math.parser math.ranges sequences vectors project-euler.common ;
4 IN: project-euler.175
5
6 ! http://projecteuler.net/index.php?section=problems&id=175
7
8 ! DESCRIPTION
9 ! -----------
10
11 ! Define f(0) = 1 and f(n) to be the number of ways to write n as a sum of
12 ! powers of 2 where no power occurs more than twice.
13
14 ! For example, f(10) = 5 since there are five different ways to express
15 ! 10: 10 = 8+2 = 8+1+1 = 4+4+2 = 4+2+2+1+1 = 4+4+1+1
16
17 ! It can be shown that for every fraction p/q (p0, q0) there exists at least
18 ! one integer n such that f(n) / f(n-1) = p/q.
19
20 ! For instance, the smallest n for which f(n) / f(n-1) = 13/17 is 241. The
21 ! binary expansion of 241 is 11110001. Reading this binary number from the most
22 ! significant bit to the least significant bit there are 4 one's, 3 zeroes and
23 ! 1 one. We shall call the string 4,3,1 the Shortened Binary Expansion of 241.
24
25 ! Find the Shortened Binary Expansion of the smallest n for which
26 ! f(n) / f(n-1) = 123456789/987654321.
27
28 ! Give your answer as comma separated integers, without any whitespaces.
29
30
31 ! SOLUTION
32 ! --------
33
34 <PRIVATE
35
36 : add-bits ( vec n b -- )
37     over zero? [
38         3drop
39     ] [
40         pick length 1 bitand = [ over pop + ] when swap push
41     ] if ;
42
43 : compute ( vec ratio -- )
44     {
45         { [ dup integer? ] [ 1 - 0 add-bits ] }
46         { [ dup 1 < ] [ 1 over - / dupd compute 1 1 add-bits ] }
47         [ [ 1 mod compute ] 2keep >integer 0 add-bits ]
48     } cond ;
49
50 PRIVATE>
51
52 : euler175 ( -- result )
53     V{ 1 } clone dup 123456789/987654321 compute [ number>string ] map "," join ;
54
55 ! [ euler175 ] 100 ave-time
56 ! 0 ms ave run time - 0.31 SD (100 trials)
57
58 SOLUTION: euler175