From dd2a41d26cfab5d551a88ff16d0b6062518d34e0 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Thu, 24 Jun 2021 19:43:49 +0100 Subject: Add bc solution to challenge 008 --- challenge-008/paulo-custodio/bc/ch-1.bc | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 challenge-008/paulo-custodio/bc/ch-1.bc 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 -- cgit