perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 384 - Task 1: Base N

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-384/#TASK1
 3 #
 4 # Task 1: Base N
 5 # ==============
 6 #
 7 # You are given a number and a base integer.
 8 #
 9 # Write a script to convert the given number in the given base integer.
10 #
11 ## Example 1
12 ##
13 ## Input: $num = 42, $base = 2
14 ## Output: 101010
15 #
16 ## Example 2
17 ##
18 ## Input: $num = 15642094, $base = 16
19 ## Output: EEADEE
20 #
21 ## Example 3
22 ##
23 ## Input: $num = 493, $base = 8
24 ## Output: 755
25 #
26 ## Example 4
27 ##
28 ## Input: $num = 2228519, $base = 36
29 ## Output: 1BRJB
30 ##
31 ## Base 36 uses numbers 0-9 and letters A-Z.
32 #
33 ## Example 5
34 ##
35 ## Input: $num = 123456789, $base = 64
36 ## Output: 7MyqL
37 ##
38 ## Base 64 (using 0-9, A-Z, a-z, and extra symbols like + and /)
39 #
40 ############################################################
41 ##
42 ## discussion
43 ##
44 ############################################################
45 #
46 # We create a list of possible digits. Then we calculate the digits one by one:
47 # - the next digit (from the rigth) is the ($num % $base)th possible digit
48 # - then we get the integer part of $num / $base to find the remainder for the
49 #   next step
50 # - we are done once we hit 0.
51 #
52 
53 use v5.36;
54 
55 my $possible_digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\"#\$\%*+-./:;,<>=?";
56 my @digits = split //, $possible_digits;
57 
58 base_n(42, 2);
59 base_n(15642094, 16);
60 base_n(493, 8);
61 base_n(2228519, 36);
62 base_n(123456789, 64);
63 
64 sub base_n($num, $base) {
65     say "Input: $num, $base";
66     my $result = "";
67     while($num > 0) {
68         my $digit = $num % $base;
69         $num = int($num / $base);
70         $result = $digits[$digit] . $result;
71     }
72     say "Output: $result";
73 }