From b91c8355370302f29a2380e43685737ff644b9f2 Mon Sep 17 00:00:00 2001
From: Luca Ferrari <fluca1978@gmail.com>
Date: Mon, 4 Apr 2022 10:21:30 +0200
Subject: Task 1 done in Pl/Perl

---
 challenge-159/luca-ferrari/postgresql/ch-2.sql | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 challenge-159/luca-ferrari/postgresql/ch-2.sql

(limited to 'challenge-159/luca-ferrari/postgresql/ch-2.sql')

diff --git a/challenge-159/luca-ferrari/postgresql/ch-2.sql b/challenge-159/luca-ferrari/postgresql/ch-2.sql
new file mode 100644
index 0000000000..da8824c0c2
--- /dev/null
+++ b/challenge-159/luca-ferrari/postgresql/ch-2.sql
@@ -0,0 +1 @@
+-- Perl Weekly Challenge 159
-- 
cgit 


From d6c45c1e8fbd72ec613baff00a8214a270f3f6cb Mon Sep 17 00:00:00 2001
From: Luca Ferrari <fluca1978@gmail.com>
Date: Mon, 4 Apr 2022 11:06:28 +0200
Subject: Task 2 done in plpgsql

---
 challenge-159/luca-ferrari/postgresql/ch-2.sql | 42 ++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)

(limited to 'challenge-159/luca-ferrari/postgresql/ch-2.sql')

diff --git a/challenge-159/luca-ferrari/postgresql/ch-2.sql b/challenge-159/luca-ferrari/postgresql/ch-2.sql
index da8824c0c2..d165df2fed 100644
--- a/challenge-159/luca-ferrari/postgresql/ch-2.sql
+++ b/challenge-159/luca-ferrari/postgresql/ch-2.sql
@@ -1 +1,43 @@
 -- Perl Weekly Challenge 159
+
+CREATE SCHEMA IF NOT EXISTS  pwc159;
+
+CREATE OR REPLACE FUNCTION
+pwc159.prime_factors( n int )
+RETURNS SETOF int
+AS $CODE$
+DECLARE
+        factor int;
+BEGIN
+        factor := 2;
+
+        WHILE ( factor <= n AND n > 1 ) LOOP
+              IF n % factor = 0 THEN
+                 n := n / factor;
+                 RETURN NEXT factor;
+              ELSE
+                factor := factor + 1;
+              END IF;
+        END LOOP;
+
+        RETURN;
+END
+$CODE$
+LANGUAGE plpgsql;
+
+
+\set n 5
+
+WITH count_prime_factors(  c, cc ) AS
+(
+        SELECT count( distinct pf ), count( pf )
+        FROM pwc159.prime_factors( :n ) pf
+)
+SELECT :n AS number,
+       CASE
+       WHEN c - cc <> 0 THEN 0
+       WHEN c % 2  = 0  THEN 1
+       ELSE -1
+       END
+
+FROM count_prime_factors;
-- 
cgit 

