aboutsummaryrefslogtreecommitdiff
path: root/challenge-157
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-03-21 21:03:53 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-03-25 17:16:57 +0100
commita96b422cdc8e90bac33fad5188165a851e981c5e (patch)
treea5dec3e08fc95c0dec9bd42e630af5b41de7bffd /challenge-157
parentbc31a0e8088e81397bd7368ab26ee61f6e535f6a (diff)
downloadperlweeklychallenge-club-a96b422cdc8e90bac33fad5188165a851e981c5e.tar.gz
perlweeklychallenge-club-a96b422cdc8e90bac33fad5188165a851e981c5e.tar.bz2
perlweeklychallenge-club-a96b422cdc8e90bac33fad5188165a851e981c5e.zip
Solution to task 2
Diffstat (limited to 'challenge-157')
-rwxr-xr-xchallenge-157/jo-37/perl/ch-2.pl67
1 files changed, 67 insertions, 0 deletions
diff --git a/challenge-157/jo-37/perl/ch-2.pl b/challenge-157/jo-37/perl/ch-2.pl
new file mode 100755
index 0000000000..6781a0b10f
--- /dev/null
+++ b/challenge-157/jo-37/perl/ch-2.pl
@@ -0,0 +1,67 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use Math::Prime::Util 'todigits';
+use experimental qw(signatures postderef);
+
+our ($tests, $examples);
+
+run_tests() if $tests || $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [-tests] [N]
+
+-examples
+ run the examples from the challenge
+
+-tests
+ run some tests
+
+N
+ Check if N is a Brazilian number. Prints the smallest base where N
+ is Brazilian or zero otherwise.
+
+EOS
+
+
+### Input and Output
+
+say is_brazilian(shift);
+
+
+### Implementation
+
+# Take the "digits" of N as keys in a hash and check if there is only
+# one such key. Returns the smallest base found or zero otherwise.
+sub is_brazilian ($n) {
+ for my $b (2 .. $n - 2) {
+ (\my %digits)->@{todigits $n, $b} = ();
+ return $b if 1 == keys %digits;
+ }
+ return 0;
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+
+ is is_brazilian(7), 2, 'example 1';
+ is is_brazilian(6), F(), 'example 2';
+ is is_brazilian(8), 3, 'example 3';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+
+ is is_brazilian(13330), 36, 'aaa(36)';
+ is is_brazilian(54871), 38, 'brazilian beyond base 36';
+ is is_brazilian(1299709), F(), '100000th prime';
+ }
+
+ done_testing;
+ exit;
+}