summaryrefslogtreecommitdiff
path: root/problem88.ijs
blob: a3909c660561cecb3bcfa38bbd3be4af50d3fe6f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
load 'stats'

NB. rank, combine, f, factorsof1, factorsof and helper are all helper functions used by factors
NB. to find all factorizations of a number. Works but is not so nice :)

rank=:{.@$@$
combine=: (*./`])@.(1: = rank)

f=: dyad define
factors=.x
length=.$factors
keep=.y{factors
rest=.(combine y~:"0 _ i.length)#factors
(*/rest),keep
)

factorsof1=: monad define
len=.$y
((y&f)"1)@comb&len len-2
)

factorsof=: monad define
cols=.<:{:$y
vals=.;factorsof1"1 y
rows=.($vals) % cols
~. (rows,cols)$vals
)

helper=: dyad : '<"1 factorsof^:x (1,$y)$y'

factors=: monad define
pfacts=.q:y
;(helper&pfacts) each i.$pfacts
)

NB. runme creates a large list of every possible factorization of numbers from 2 to 2*k
NB. Then it goes over that list and updates the numbers array with the smallest
NB. product-sum number. product-sum numbers from a set of factors such as 3 2 2 by adding
NB. enough ones, since that makes the sum large enough. the k for which a set of factors
NB. can be used can be calculated by (prod-sum)+$factors
NB. and can be read as "number of ones needed" + "number of factors"
NB. The slowest part of the program is finding all factorizations of numbers.

runme=: monad define
maxk=.y
maxn=.2*maxk
facts=. ; factors each 2+i.(maxn-1)
numbers=. maxn$_
factorcount=.$facts
index=.0
while. index < factorcount do.
	nums=.>index{facts
	index=. >:index
	sum=.+/nums
	prod=.*/nums
	n=.(prod-sum)+$nums NB. any factors can be used when padded with enough ones :)
	oldprod=.n{numbers
	if. prod < oldprod do.
		numbers=.prod n} numbers
	end.
end.
numbers=. (-maxk-1)}. 2}. numbers NB. drop for k=0,1, and take (maxk-1) elements
+/~.numbers
)