perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 359 - Task 1: Digital Root

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-359/#TASK1
 3 #
 4 # Task 1: Digital Root
 5 # ====================
 6 #
 7 # You are given a positive integer, $int.
 8 #
 9 # Write a function that calculates the additive persistence of a positive
10 # integer and also return the digital root.
11 #
12 ### Digital root is the recursive sum of all digits in a number until a single
13 ### digit is obtained.
14 #
15 ### Additive persistence is the number of times you need to sum the digits to
16 ### reach a single digit.
17 #
18 ## Example 1
19 ##
20 ## Input: $int = 38
21 ## Output: Persistence  = 2
22 ##         Digital Root = 2
23 ##
24 ## 38 => 3 + 8 => 11
25 ## 11 => 1 + 1 => 2
26 #
27 #
28 ## Example 2
29 ##
30 ## Input: $int = 7
31 ## Output: Persistence  = 0
32 ##         Digital Root = 7
33 #
34 #
35 ## Example 3
36 ##
37 ## Input: $int = 999
38 ## Output: Persistence  = 2
39 ##         Digital Root = 9
40 ##
41 ## 999 => 9 + 9 + 9 => 27
42 ## 27  => 2 + 7 => 9
43 #
44 #
45 ## Example 4
46 ##
47 ## Input: $int = 1999999999
48 ## Output: Persistence  = 3
49 ##         Digital Root = 1
50 ##
51 ## 1999999999 => 1 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 => 82
52 ## 82 => 8 + 2 => 10
53 ## 10 => 1 + 0 => 1
54 #
55 #
56 ## Example 5
57 ##
58 ## Input: $int = 101010
59 ## Output: Persistence  = 1
60 ##         Digital Root = 3
61 ##
62 ## 101010 => 1 + 0 + 1 + 0 + 1 + 0 => 3
63 #
64 ############################################################
65 ##
66 ## discussion
67 ##
68 ############################################################
69 #
70 # We need a simple loop that splits the current value of $int into
71 # its digits and then calculates the sum. The former can be done
72 # via split(), the latter can be done via sum() from List::Util, so
73 # this turns into a oneliner (plus another line for incrementing our
74 # persistence variable).
75 
76 use v5.36;
77 use List::Util qw(sum);
78 
79 digital_root(38);
80 digital_root(7);
81 digital_root(999);
82 digital_root(1999999999);
83 digital_root(101010);
84 
85 sub digital_root($int) {
86     say "Input: $int";
87     my $persistence = 0;
88     while(length($int) > 1) {
89         $persistence++;
90         $int = sum(split //, $int);
91     }
92     say "Output: Persistence = $persistence, Digital Root = $int";
93 }