aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaulo Custodio <pauloscustodio@gmail.com>2021-06-24 19:43:49 +0100
committerPaulo Custodio <pauloscustodio@gmail.com>2021-06-24 19:43:49 +0100
commitdd2a41d26cfab5d551a88ff16d0b6062518d34e0 (patch)
treef78914a6565d1fa0d0eed8c84be5274fdd102514
parent47c31b2fddb7e0695795d799aaf1cdbf82083a3f (diff)
downloadperlweeklychallenge-club-dd2a41d26cfab5d551a88ff16d0b6062518d34e0.tar.gz
perlweeklychallenge-club-dd2a41d26cfab5d551a88ff16d0b6062518d34e0.tar.bz2
perlweeklychallenge-club-dd2a41d26cfab5d551a88ff16d0b6062518d34e0.zip
Add bc solution to challenge 008
-rw-r--r--challenge-008/paulo-custodio/bc/ch-1.bc49
1 files changed, 49 insertions, 0 deletions
diff --git a/challenge-008/paulo-custodio/bc/ch-1.bc b/challenge-008/paulo-custodio/bc/ch-1.bc
new file mode 100644
index 0000000000..12053a2445
--- /dev/null
+++ b/challenge-008/paulo-custodio/bc/ch-1.bc
@@ -0,0 +1,49 @@
+#!/usr/bin/bc -ql
+
+/*
+Challenge 008
+
+Challenge #1
+Write a script that computes the first five perfect numbers. A perfect number
+is an integer that is the sum of its positive proper divisors (all divisors
+except itself). Please check Wiki for more information.
+This challenge was proposed by Laurent Rosenfeld.
+*/
+
+scale = 0
+
+num = read()
+
+define is_prime(n) {
+ auto i
+ if (n <= 1) return 0
+ if (n <= 3) return 1
+ if ((n % 2) == 0 || (n % 3) == 0) return 0
+ for (i = 5; i*i <= n; i += 6) {
+ if ((n % i) == 0 || (n % (i + 2)) == 0) return 0
+ }
+ return 1
+}
+
+define next_prime(n) {
+ if (n <= 1) return 2
+ n = n+1
+ while (!is_prime(n)) n = n+1
+ return n;
+}
+
+p = 1
+define next_perfect() {
+ auto f
+ while (1) {
+ p = next_prime(p)
+ f = (2 ^ p) - 1
+ if (is_prime(f)) return (2 ^ (p-1)) * f
+ }
+}
+
+for (i = 0; i < num; i++) {
+ print next_perfect(), "\n"
+}
+
+quit