aboutsummaryrefslogtreecommitdiff
path: root/challenge-156/luca-ferrari/postgresql/ch-2.sql
blob: ac9d22739c831783578a5228f2d04743f753f304 (plain)
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
CREATE SCHEMA IF NOT EXISTS pwc156;

CREATE OR REPLACE FUNCTION
pwc156.weird( int )
RETURNS bool
AS $CODE$

use Algorithm::Knapsack;
my @divisors;

for my $i ( 2 .. $_[0] - 1 ) {
   push @divisors, $i if $_[0] % $i == 0;
}

my $sum = 0;
for my $i ( @divisors ) {
   $sum += $i;
}


return 0 if $sum <= $_[0];

my $knapsack = Algorithm::Knapsack->new(
    capacity => $_[0],
    weights  => \@divisors,
);
 
$knapsack->compute();
 
foreach my $solution ($knapsack->solutions()) {
    my @founds = @divisors[ $solution->@* ];
    my $sum = 0;
    $sum += $_ for ( @founds );
    return 0 if $sum == $_[0];
 
}


return 1;
$CODE$
LANGUAGE plperlu;




SELECT n
FROM generate_series( 1, 100 ) n
WHERE pwc156.weird( n );